Sub topic 4
Hydrating the page with hydrateRoot
This chapter shows how the browser attaches React to HTML that the server already sent. It assumes you know function components, useState, useEffect, and basic Express. It also assumes you have a bundler that builds a client entry file.
What hydrateRoot does
hydrateRoot is the function from react-dom/client that starts React on a page whose HTML was rendered on the server. It does not build new DOM. React renders your components in the browser, compares the result with the existing DOM, and reuses the nodes it finds. It then attaches event handlers to those nodes.
Compare this with createRoot. createRoot clears the container and builds all the DOM from scratch. Use it for client-only apps. Use hydrateRoot only when the server produced the markup.
The client entry
The client entry is short:
import { hydrateRoot } from 'react-dom/client';
import App from './App.js';
hydrateRoot(document, <App />);The first argument is the DOM node that holds the server HTML. Here it is document, because App renders the whole <html> element, including <head> and <body>. If your server renders only a fragment inside <div id="root">, pass that element instead.
The second argument is the same React tree the server rendered. The server and the client must render the same component with the same props. If they differ, you get a hydration mismatch, which a later chapter covers.
How the pieces connect
The server sends HTML that includes a script tag for the client bundle. The browser shows the HTML right away. When the script loads, it runs hydrateRoot.
Between the HTML arriving and hydration finishing, the page is visible but buttons do nothing. This gap is the main cost of SSR, so keep the client bundle small.
Linking the script from the server
The server must tell the browser which script to load. In the Express route, the bootstrapScripts option does this:
const { pipe } = renderToPipeableStream(<App />, {
bootstrapScripts: ['/static/client.js'],
onShellReady() {
pipe(res);
}
});React adds a <script src="/static/client.js" async> tag to the output. The path must match a file your server actually serves, such as the express.static('dist') mount at /static.
Options
hydrateRoot takes an optional third argument. The one you will use most is onRecoverableError, which reports errors React fixed by itself, such as a mismatch that forced client rendering. A later chapter covers it.
Exercise
Your server renders <App /> into <div id="root">, and App renders only the contents of that div. Write the client entry line that hydrates it, and say what would happen if you used createRoot instead.
Show answer
hydrateRoot(document.getElementById('root'), <App />); With createRoot, React would clear the div and rebuild the DOM from scratch. The server HTML would be thrown away and you would lose the speed benefit of SSR.