← Back to Chapters

Hydration & Client Rendering

? Hydration & Client Rendering

⚛️ Introduction

In React, the UI can be rendered on the client (browser) or the server (Node.js). When HTML is rendered on the server and then made interactive on the client, this process is called hydration.

Understanding hydration vs client rendering is crucial when working with frameworks like Next.js, Remix, or using React’s Server Components.

? Client-Side Rendering (CSR)

In CSR, the browser downloads a mostly empty HTML page and runs React on the client to generate and render the UI dynamically.

? View Code Example
// Client-side React rendering entry point
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
  • Initial HTML is minimal.
  • React builds the UI entirely in the browser.
  • Slower initial load, faster navigation later.

? Server-Side Rendering (SSR)

In SSR, HTML is generated on the server and sent to the client. This improves SEO and first load performance.

? View Code Example
// Server-side rendering using Express and ReactDOMServer
import express from "express";
import ReactDOMServer from "react-dom/server";
import App from "./App";

const app = express();

app.get("/", (req, res) => {
const html = ReactDOMServer.renderToString(<App />);
res.send(`<html><body><div id="root">${html}</div></body></html>`);
});

app.listen(3000);

? What is Hydration?

Hydration is the process where React attaches event listeners and internal state logic to server-rendered HTML.

? View Code Example
// Hydrating server-rendered HTML on the client
import React from "react";
import { hydrateRoot } from "react-dom/client";
import App from "./App";

hydrateRoot(document.getElementById("root"), <App />);

⚙️ Hydration Lifecycle Overview

  1. Server renders static HTML.
  2. Browser displays HTML immediately.
  3. React loads JavaScript and hydrates.
  4. Interactivity becomes available.

? Interactive Simulation

This simulates the "Uncanny Valley" where content is visible but not yet interactive.

Current State: ? Static HTML
0

Try clicking "Increment" above. Nothing happens because JS isn't attached.

? Hydration vs Rehydration

  • Hydration: Attaching logic to existing HTML.
  • Rehydration: Rebuilding UI after mismatch.
  • Mismatch causes hydration warnings.

? Tips

  • Ensure server and client output match.
  • Avoid random values during SSR.
  • Use suppressHydrationWarning when needed.

? Try This

  1. Create an SSR app with Express.
  2. Hydrate it on the client.
  3. Compare CSR vs SSR performance.
  4. Trigger a hydration mismatch intentionally.

Goal: Understand how hydration bridges server HTML and client interactivity.