hydrateRoot
Hydrates a React application in a browser DOM container that was previously rendered by a React server API.Reference
hydrateRoot(container, reactNode, options?)
Call hydrateRoot to attach React to existing HTML that was rendered by React in a server environment.
/src/client/ReactDOMRoot.js:274-358
Parameters
Document | Element
required
The DOM element that contains the server-rendered HTML. Must match the container used on the server.Validation:
- Must be a valid DOM element or Document
- Should contain server-rendered React HTML
- Cannot be a DocumentFragment (unlike createRoot)
ReactNode
required
The React node that was used to render the existing HTML on the server. This must be identical to what was rendered on the server.
HydrateRootOptions
Optional configuration object for hydration.
Returns
RootType
A root object with
render, unmount, and unstable_scheduleHydration methods.root.render(reactNode)
Updates the hydrated root after initial hydration. Works the same as createRoot().render().
root.unmount()
Unmounts the React tree and cleans up. Same behavior as createRoot().unmount().
root.unstable_scheduleHydration(target)
Schedules eager hydration of a specific DOM node.
Usage Examples
Basic SSR Hydration
Server (Node.js):With Error Tracking
With Suspense Boundaries
Progressive Hydration
Handling Hydration Mismatches
Hydration mismatches occur when the server-rendered HTML doesn’t match the client-rendered React tree.Common Causes
- Incorrect nesting - Invalid HTML structure
- Browser extensions - Modify the DOM
- Date/time - Server and client timestamps differ
- Random values - Using Math.random() or Date.now()
- Environment differences - window/document available only on client
Example: Date/Time Mismatch
Problem:Debugging Hydration Errors
Enable detailed hydration logging in development:- Which component caused the mismatch
- What the server rendered
- What the client expected
- The component stack trace
TypeScript
Migration from React 17
Before (React 17)
After (React 18+)
Performance Optimization
Selective Hydration
React 18 automatically prioritizes hydration based on user interactions:Streaming SSR + Selective Hydration
Server:- HTML streams to browser before all data is ready
- Page becomes interactive sooner
- React hydrates high-priority content first
Common Pitfalls
Don’t modify DOM before hydration
Ensure server/client parity
Browser Compatibility
Same requirements ascreateRoot:
- Modern browsers (Chrome 90+, Firefox 88+, Safari 14.1+, Edge 90+)
- ES6 features: Map, Set, Promise
- DOM features: Element, Document
Related APIs
- createRoot - For client-only rendering
- renderToPipeableStream - Server rendering (Node.js)
- renderToReadableStream - Server rendering (Web Streams)