Open In App

Server-Side Rendering (SSR) with React Hooks

Server-side rendering (SSR) is a technique used to render web pages on the server side and send the fully rendered page to the client’s browser. This approach offers benefits such as improved SEO and faster initial page loads. With the introduction of React Hooks, SSR implementation has become even more streamlined. In this article, we’ll explore how to support React Hooks for Server-side Rendering.

We will learn about the following concepts of SSR with React Hooks:



Understanding Server-side Rendering (SSR):

Server-side rendering involves generating HTML on the server and sending it to the client, where it’s hydrated into a fully interactive page. This contrasts with traditional client-side rendering, where JavaScript is responsible for generating the HTML in the browser.



Leveraging React Hooks for Server-side Rendering(SSR):

Benefits of SSR with React Hooks:

Examples of Server Side Rendering with React Hooks

Example 1: Below is an example to support React Hooks for server-side rendering.




import React, {
    useState,
    useEffect
} from 'react';
 
const MyComponent = () => {
    const [data, setData] = useState(null);
 
    useEffect(() => {
        // Simulate data fetching on the server side
        fetchData().then((result) => {
            setData(result);
        });
    }, []);
 
    return (
        <div>
            {data ? (
                <p>Data: {data}</p>
            ) : (
                <p>Loading...</p>
            )}
        </div>
    );
};
 
// Simulated server-side data fetching function
const fetchData = () => {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve('Server-side data');
        }, 1000);
    });
};
 
export default MyComponent;

Output:

Output

Example 2: Below is an example of server-side rendering with React Hooks.




// App.js
import React, {
    useState,
    useEffect
} from 'react';
 
const App = () => {
    const [data, setData] = useState(null);
 
    useEffect(() => {
        fetchData().then((result) => {
            setData(result);
        });
    }, []);
 
    const fetchData = async () => {
        try {
            const response = await
                fetch('https://jsonplaceholder.typicode.com/posts/1');
            const jsonData = await response.json();
            return jsonData;
        } catch (error) {
            console.error('Error fetching data:', error);
            return null;
        }
    };
 
    return (
        <div>
            <h1>Server-Side Rendering with React Hooks</h1>
            {data ? (
                <div>
                    <h2>Title: {data.title}</h2>
                    <p>Body: {data.body}</p>
                </div>
            ) : (
                <p>Loading...</p>
            )}
        </div>
    );
};
 
export default App;




// server.js
import express from 'express';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import App from './App';
 
const app = express();
 
app.use(express.static('public'));
 
app.get('*', (req, res) => {
  const appMarkup = ReactDOMServer.renderToString(<App />);
  res.send(`
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Server-Side Rendering</title>
      </head>
      <body>
        <div id="root">${appMarkup}</div>
        <script src="/bundle.js"></script>
      </body>
    </html>
  `);
});
 
app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

Output:

Output

Conclusion:

Server-Side Rendering with React Hooks offers a powerful way to enhance performance, SEO, and user experience in web applications. By leveraging hooks like `useState` and `useEffect`, you can efficiently implement SSR and ensure consistent rendering between the server and client sides. With this approach, you’ll be well-equipped to build high-performance React applications.


Article Tags :