Sub topic 3
What hydration does to server HTML
Hydration is the step where React attaches itself to HTML that the server already produced. This chapter explains what React does during that step and what it does not do. It assumes you can write function components with useState and useEffect. It also assumes you know that renderToString turns a component tree into an HTML string. The next chapter covers the hydrateRoot API in detail. Here the focus is the working model.
The problem hydration solves
HTML from the server is a finished document. The browser can paint it right away, so the user sees content early. But that HTML is inert. A <button> in it has no onClick handler, because event handlers are JavaScript functions and cannot be written into an HTML string. React state does not exist yet either.
Hydration closes that gap. React runs your components in the browser, matches the result against the existing DOM nodes, and connects handlers and state to them. The page then behaves like an app that was rendered in the browser from the start.
What React does during hydration
Hydration is a render, not a copy. React does these things in order:
- It calls your components in the browser with the same props they had on the server. This builds React's internal tree (the fiber tree), which holds state, hooks, and the list of elements each component returned.
- As it walks that tree, it looks at the DOM node that already exists at each position instead of creating a new node.
- It checks that the node matches what the component returned: same element type, same text, same attributes.
- It attaches event handling. React handles events by listening at the root, so "attaching" a handler means recording it in the fiber tree, not calling
addEventListeneron every node. - It runs effects.
useEffectanduseLayoutEffectcallbacks do not run on the server, so the first time they run is after hydration.
The key idea is that hydration reuses DOM nodes but still executes all of your component code. The cost of hydration is therefore the cost of a full client render minus the DOM creation.
A worked example
Here is a component with state. Assume the server rendered it with renderToString.
import { useState } from 'react';
export default function App() {
const [count, setCount] = useState(0);
return (
<html lang="en">
<body>
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
<script src="/static/client.js" async></script>
</body>
</html>
);
}The server sends HTML like this, with no trace of onClick:
<!DOCTYPE html><html lang="en"><body><button>Clicked <!-- -->0<!-- --> times</button><script src="/static/client.js" async=""></script></body></html>The <!-- --> comments separate adjacent text pieces. Without them the browser would merge Clicked , 0, and times into one text node, and React could not match them to the three pieces it expects. Hydration relies on details like this.
The client entry then hydrates:
import { hydrateRoot } from 'react-dom/client';
import App from './App.js';
hydrateRoot(document, <App />);Before this script runs, clicking the button does nothing. After it runs, React has called App in the browser, reused the existing <button>, and recorded its onClick. The first click now updates state and re-renders as in any React app.
What hydration does not do
Several misconceptions cause real bugs, so it helps to name them.
- It does not repair HTML. React assumes the server HTML is what the client render would produce. It does not diff and patch every difference. When they disagree, behavior depends on the kind of difference, and that is the subject of the mismatch chapters later in this tutorial.
- It does not skip work. Components, hooks, and any computation in render run again in the browser. Expensive render logic costs time twice.
- It does not run effects early. Effects wait until after hydration, so code in an effect cannot influence the server HTML.
- It does not fetch your server data again by itself. If a component needs data, the client render must have the same data available, usually passed in with the page. Otherwise the first client render differs from the HTML.
- It does not make the page interactive before the JavaScript arrives. Between the first paint and the end of hydration, the page looks ready but is not.
The gap between paint and interactivity
The window between "the user can see the page" and "the page responds" is the main cost of SSR. Its length depends on bundle size, network speed, and how much render work React has to do.
| Moment | What the user sees | What works |
|---|---|---|
| HTML arrives | Full content once parsed | Links and native form submits |
| JavaScript downloads | Same content | Links and native form submits |
| Hydration runs | Same content, possibly a frozen feel | Links and native form submits |
| Hydration completes | Same content | Everything React controls |
Native browser behavior still works during the gap, because it needs no React. A link navigates and a plain form submits. A click on a button with only an onClick is lost, because no handler exists yet. (React replays some discrete events, such as clicks, that happen on a part of the page while it is waiting to hydrate. Do not rely on this to hide a long gap.)
Why the client render must match
React does the matching because it needs to trust the DOM it adopts. When it reuses the <button>, it assumes that button has the right text, attributes, and position among its siblings. Later updates then change only the parts that differ between renders. If the server HTML held something else, React would be updating a DOM that does not reflect its own tree.
This leads to a practical rule for the first client render. It must produce the same output as the server render, given the same props and data. Anything that differs between server and browser must wait until after hydration. Typical examples are the current time, random numbers, and checks of window. Effects are the usual tool for that, and a later chapter covers it.
Common errors at this stage
- Hydrating with a different root. The tree passed to
hydrateRootmust be the same tree the server rendered, including wrapper components. If the server rendered<App />and the client hydrates<Layout><App /></Layout>, the output differs. - Loading the script too late or not at all. The page paints and stays dead. Check that the response includes the script tag, as the example above does, and that the path resolves.
- Using
createRooton server HTML.createRootclears the container and renders from scratch. The page may look fine, but you lose the benefit of the server HTML and may see a flash. - Assuming handlers are in the HTML. Inspecting the server response for
onclickshows nothing, and that is expected.
Summary of the model
Server HTML gives the user something to read quickly. Hydration then runs your components in the browser, adopts the existing DOM nodes, wires up events, and starts effects. It succeeds cleanly only when the first client render matches the HTML. The rest of this tutorial covers the API for starting it, what goes wrong when the match fails, and how streaming lets parts of the page hydrate on their own.
Exercise
A page is server-rendered with renderToString. A user clicks a button with an onClick handler before the JavaScript bundle has finished downloading. What happens, and why? Name two things React does during hydration that make the button work afterward.
Show answer
Nothing happens on the click, because the server HTML contains the <button> element but not the handler, which is a JavaScript function that exists only after the bundle runs. During hydration, React (1) calls the components in the browser and matches the result to the existing DOM nodes, reusing the <button>, and (2) records the onClick handler in its tree and attaches event handling at the root. Effects also run for the first time after hydration.
Exercise
A teammate adds console.log('rendered') and a call to analytics.track('view') directly in a component's render body. After enabling SSR, the analytics service reports two views per page load, one from the server and one from the browser. Explain why, and say where the analytics.track call should go.
Show answer
The component function runs on the server to produce the HTML and runs again in the browser during hydration, so any call in the render body runs in both places. Move analytics.track('view') into a useEffect with an empty dependency array. Effects do not run on the server, so the call happens once, after hydration, in the browser.