Sub topic 4
Hydrating the page with hydrateRoot
This chapter assumes you know function components, useState and useEffect, and basic Node.js with Express. You should also have read the previous chapters, which cover rendering components to an HTML string and what hydration does at a high level. Here you will write the client side: the call that attaches React to HTML the server already produced.
What hydrateRoot does
hydrateRoot is the client-side entry point for server-rendered pages. It lives in react-dom/client, and its signature is:
hydrateRoot(domNode, reactNode, options?)domNodeis the DOM node that contains the server HTML. It is oftendocument, or a container such as#root.reactNodeis the React tree to attach, usually<App />.optionsis optional. The ones you will use most areonRecoverableErrorandidentifierPrefix.
It returns a root object with render() and unmount() methods.
The simplest client entry for a page whose App renders the whole <html> element is:
import { hydrateRoot } from 'react-dom/client';
import App from './App.js';
hydrateRoot(document, <App />);During hydration React renders App in the browser, as it would for any render. Instead of creating DOM nodes, it walks the existing DOM in step with the tree it just rendered and claims each node. It then attaches event handlers, and the page becomes interactive. If a node in the existing DOM does not match what the component tree expects, React treats that as a hydration mismatch. The next chapter covers mismatches in detail.
A complete minimal setup
The server and the client must render the same component with the same props. Here is a shared App.js that renders the full document:
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}
export default function App() {
return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<title>Hydration demo</title>
</head>
<body>
<h1>Hello from the server</h1>
<Counter />
</body>
</html>
);
}On the server, the Express route from the streaming example sends this HTML and includes bootstrapScripts: ['/static/client.js']. React adds a <script async> tag for that file to the output. The browser fetches the bundle, runs hydrateRoot(document, <App />), and the button starts responding to clicks.
If you render only part of the page, give React a container instead:
import { hydrateRoot } from 'react-dom/client';
import App from './App.js';
const container = document.getElementById('root');
hydrateRoot(container, <App />);On the server, the HTML for <App /> must then sit inside <div id="root">…</div>. Any whitespace or comment inserted between the opening tag and the first child can become a text node that React does not expect. Generate the container markup carefully, and avoid pretty-printing the HTML that goes inside it.
The page's timeline
The page is visible long before it is interactive. The browser paints the HTML as soon as it arrives. The JavaScript bundle then downloads, parses and runs, and only after that does hydration attach handlers.
A click during the gap between paint and hydration is not lost in every case. React replays some discrete events, such as clicks, once the target component has hydrated. Do not rely on this for anything important. Keep the bundle small, so the gap stays short.
Rules that keep hydration working
- Render the same tree. The component, props and initial state must produce the same markup as the server did. If the server fetched data and passed it to
App, the client needs the same data. A common approach is to serialize it into the HTML, for example as JSON in a script tag, and read it back before callinghydrateRoot. - Use
hydrateRoot, notcreateRoot, for server HTML.createRoot(container).render(<App />)discards the container's contents and builds the DOM again. The page works, but you lose the benefit of SSR and may see a flash. - Call it once per root. To update a hydrated root later, call
root.render(<App newProps />)on the objecthydrateRootreturned. This is rarely needed, because state and context normally drive updates. - Match library versions. Server and client bundles should use the same React version. Differing versions can produce markup that does not match.
- Do not edit the server DOM before hydration. Scripts that insert nodes into the container before React runs can cause mismatches. Place such scripts outside the hydrated container, or run them after hydration.
Options worth knowing
onRecoverableError is called when React recovers from an error, such as a mismatch that forced it to re-render a part of the page on the client. Without it, React logs to the console. With it, you can send the error to a monitoring service:
import { hydrateRoot } from 'react-dom/client';
import App from './App.js';
hydrateRoot(document, <App />, {
onRecoverableError(error, errorInfo) {
console.error('Recoverable error:', error);
console.error('Component stack:', errorInfo.componentStack);
}
});identifierPrefix is a string that React puts in front of ids generated by useId. If two separate React roots on one page both use useId, give each root a different prefix. The server render must use the same prefix, so pass identifierPrefix to renderToPipeableStream as well. Otherwise the ids differ and the match fails.
Edge cases
- Browser extensions. Extensions can add attributes or elements to
<html>,<head>or<body>, and a user can then see a mismatch warning that you cannot reproduce. Test in a clean profile before assuming your code is at fault. React tolerates some extra elements that other scripts add to<head>and<body>, but not everything. - Attribute differences. When text content differs, React falls back to client rendering. For attribute differences, React does not guarantee it will repair them, so the old attribute value may remain in the DOM.
- Missing bundle. If
client.jsfails to load, the page still shows server HTML, but nothing is interactive. Check the network tab for 404 errors on the script path. - Two entry points. If you render
<html>insideApp, hydratedocument. If you hydrate a container,Appmust not render<html>, because an<html>element cannot sit inside a<div>.
Summary
hydrateRoot(domNode, reactNode, options)attaches React to server HTML without rebuilding the DOM.- Hydrate
documentwhenApprenders<html>. Hydrate a container whenApprenders only the content inside it. - The client tree must match what the server rendered, including props, data and
useIdprefixes. - Pass
onRecoverableErrorto see and report errors that React recovers from.
Exercise
Your server renders <App /> into <div id="root">, and your client entry calls createRoot(document.getElementById('root')).render(<App />). The page looks right and works, but the page flashes when it loads. What is wrong, and what should you change?
Show answer
createRoot ignores the existing server HTML and renders the whole tree again on the client, which replaces the DOM. Replace it with hydrateRoot(document.getElementById('root'), <App />) so React reuses the existing nodes and only attaches event handlers.