What is React Hydration?

React hydration

React hydration is the process of attaching event handlers and updating the DOM generated by server-rendered HTML to make it interactive and dynamic. It's a critical step in server-side rendering (SSR) with React, where initial HTML content is rendered on the server and sent to the client for faster page loads and better SEO.

During hydration, React compares the server-rendered HTML with the client-side React components. It attaches event listeners and sets up the necessary JavaScript to make the HTML interactive. This process bridges the gap between the static HTML sent from the server and the dynamic behavior expected in a React application.

How hydration works in React?

  1. Server-Side Rendering (SSR)

    • When a user requests a page, the server renders the initial HTML content, including React components, based on the requested URL and data.
    • The server sends this HTML to the client as the initial response.
  2. Client-Side Hydration

    • When the browser receives the HTML, it starts parsing and rendering it.
    • As soon as the necessary JavaScript bundles are downloaded and executed, React on the client side takes over.
    • React compares the server-rendered HTML with the client-side component tree. It identifies the parts of the DOM that need to be updated to match the dynamic behavior of the React components.
    • Event listeners are attached, and the DOM is updated as needed to make the page interactive.
    • Once hydration is complete, the React application becomes fully interactive, and further updates are managed by React's reconciliation algorithm.

Hydration ensures that React applications provide a seamless transition from server-rendered content to client-side interactivity. It allows developers to leverage the benefits of server-side rendering while still maintaining a rich, dynamic user experience on the client side.

How hydration is typically implemented in a React application?

Here's a simplified example of how hydration is typically implemented in a React application:

// Server-side rendering
const initialHtml = ReactDOMServer.renderToString(<App />);
res.send(`
  <!DOCTYPE html>
  <html>
    <head>
      <title>My App</title>
    </head>
    <body>
      <div id="root">${initialHtml}</div>
      <script src="/bundle.js"></script>
    </body>
  </html>
`);

// Client-side hydration
ReactDOM.hydrate(<App />, document.getElementById('root'));

In this example, ReactDOMServer.renderToString is used on the server to render the initial HTML, while ReactDOM.hydrate is used on the client to hydrate the server-rendered HTML and make it interactive.