Open In App

Server-Side Rendering (SSR) with React Hooks

Last Updated : 27 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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):

  • useState and useEffect Hooks: The `useState` and `useEffect` hooks are fundamental for managing state and performing side effects in functional components. When it comes to SSR, these hooks allow you to initialize state and fetch data on the server side before sending the fully rendered page to the client.
  • useLayoutEffect Hook: While `useEffect` is suitable for side effects that don’t block the browser painting, `useLayoutEffect` is executed synchronously immediately after DOM mutations. This can be useful for SSR scenarios where you need to ensure synchronous operations.
  • Server-Side Data Fetching: Utilize the `useEffect` hook with empty dependency array to perform data fetching on the server side. This ensures that data is fetched before rendering the component.
  • State Initialization: Use `useState` hook to initialize state with data fetched on the server side. This ensures that the initial state is consistent between the server and the client.

Benefits of SSR with React Hooks:

  • Improved Performance: SSR with React Hooks allows you to fetch data on the server side, leading to faster initial page loads and improved performance.
  • SEO Benefits: Search engines can crawl and index content more effectively with server-rendered pages, boosting SEO rankings.
  • Enhanced User Experience: By pre-rendering content on the server side, users experience faster page loads and improved perceived performance.

Examples of Server Side Rendering with React Hooks

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

Javascript




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:

gfg66

Output

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

Javascript




// 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;


Javascript




// 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:

gfg66

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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads