Sub topic 1
Why Render on the Server: CSR and SSR Trade-offs
Prerequisites
This chapter assumes you know React function components, JSX, hooks, basic HTML, and basic Node.js HTTP servers.
Client-Side and Server-Side Rendering
Client-side rendering (CSR) sends a small HTML shell and JavaScript to the browser. React then runs in the browser and creates the page. CSR can make later navigation fast, but the first meaningful content depends on downloading and executing JavaScript.
Server-side rendering (SSR) creates the initial HTML on the server and sends it to the browser. Users can see content sooner, and search engines can read the page without running the application first. SSR costs server CPU, increases request complexity, and still needs JavaScript if the page must become interactive.
| Approach | Initial content | Server work | Browser work |
|---|---|---|---|
| CSR | After JavaScript runs | Low | Higher |
| SSR | In the first response | Higher | Hydration |
Turning Components into HTML
React can render a component tree to an HTML string with renderToString. An HTTP server can place that string in a response.
import express from 'express';
import { renderToString } from 'react-dom/server';
import App from './App.js';
const app = express();
app.get('/', (_req, res) => {
const html = renderToString(<App />);
res.type('html').send(`<!doctype html>
<html><body><div id="root">${html}</div>
<script type="module" src="/client.js"></script>
</body></html>`);
});
app.listen(3000);What Hydration Does to Server HTML
Hydration is the process of attaching React behavior to HTML that already exists. React renders the same tree in the browser, compares it with the server output, and connects event handlers. It should reuse the existing DOM instead of replacing it.
Hydrating with `hydrateRoot`
The client entry point calls hydrateRoot on the container holding the server-rendered tree.
import { hydrateRoot } from 'react-dom/client';
import App from './App.js';
hydrateRoot(document.getElementById('root'), <App />);The server and client must use compatible component code and data. A component should not read browser-only values during its first render when those values were unavailable on the server.
Hydration Mismatches and Their Cost
A hydration mismatch occurs when the server HTML differs from the client’s first render. Common causes include current time, random values, browser checks, different data, and invalid HTML nesting.
React may warn, discard part of the server DOM, or switch that section to client rendering. The result can include flicker, lost server work, incorrect attributes, and slower interaction. Fix the source of the difference rather than hiding the warning.
Exercise
Why can SSR still require a client-side JavaScript bundle?
Show answer
SSR sends the initial HTML, but hydration needs the client bundle to attach React event handlers and make components interactive.