Capítulo 95 de 116

Chapter 95: hydrateRoot

Core Idea

hydrateRoot(domNode, reactNode, options?) attaches React to DOM nodes that were already server-rendered, reusing the existing markup and attaching event listeners rather than tearing down and re-creating the DOM from scratch — the client half of the SSR story.

Key Concepts

  • Signature: hydrateRoot(domNode, reactNode, options?)domNode is the container already holding server-rendered HTML, reactNode is the same JSX tree the server rendered (must match, or hydration mismatches occur).
  • The tree must match the server output. React reuses the existing DOM by walking it and confirming it matches what the client-side render would produce — genuine mismatches (server rendered one thing, client would render another) cause React to log an error and re-render that mismatched part from scratch, discarding the preserved DOM's benefit there.
  • Common mismatch sources: rendering something environment-dependent that differs between server and client (current date/time, window-only APIs, locale-dependent formatting) without guarding it — a frequent source of hydration warnings.
  • onRecoverableError option: hydration mismatches that React can recover from (by patching the DOM) still fire this callback, letting an app log/monitor them even though the user doesn't see a broken page.
  • Distinct from createRoot: don't use hydrateRoot on an empty container (nothing to reconcile against) and don't use createRoot on server-rendered markup you want preserved (it would discard and rebuild the DOM instead of reusing it).

Code Examples

import { hydrateRoot } from 'react-dom/client';

hydrateRoot(document.getElementById('root'), <App />);
  • What it demonstrates: attaching to server-rendered markup already present in #root, matching it exactly with the same <App /> tree the server used.

Key Takeaways

  1. Use hydrateRoot specifically when the server already produced the initial HTML — it reuses that DOM instead of rebuilding it.
  2. The client tree passed here must match what the server actually rendered, or React logs mismatch warnings and patches the difference.
  3. Environment-dependent render output (dates, window, locale) is the classic source of hydration mismatches — guard it explicitly (e.g. render a placeholder on first client render, then update after mount).

Connects To

  • Ch 94 (createRoot): the non-hydrating alternative for purely client-rendered apps.
  • Ch 110 (Server Components) and Ch 106-107 (renderToPipeableStream / renderToReadableStream): the server-side half that produces the HTML this function hydrates.