Hydrate matching initial markup
Hydration starts from a shared initial snapshot
Hydration is the process of connecting React to markup already present in the browser. The first client render should describe the same tree, text, attributes and IDs as the server. Time zones, locale, random values, browser-only APIs, invalid HTML nesting and changed data can cause discrepancies. Use the same data snapshot and deterministic formatting on both sides, then update client-specific information after hydration. The next three blocks are one paired integration fixture, not independent default Apps. React 18 or 19 supports these APIs; actual server/client builds are pending.
import React,{useId,useState,useEffect} from 'react';export const initial={name:'Basil',updated:'2026-01-15T09:30:00Z'};export function utcLabel(value){return new Date(value).toISOString().slice(0,16).replace('T',' ')+' UTC';}export function serializeInitial(data){return JSON.stringify(data).replace(/</g,'\\u003c');}export function Garden({data}) { const id=useId(); const [count,setCount]=useState(0); const [ready,setReady]=useState(false); useEffect(()=>setReady(true),[]); return <main><h1>{data.name}</h1><p>Updated: {utcLabel(data.updated)}</p><label htmlFor={id}>Seed note</label><input id={id}/><button type="button" onClick={()=>setCount(n=>n+1)}>Count: {count}</button><p>{ready?'Browser ready':'Preparing interaction'}</p></main>;}The initial heading is Basil, the timestamp is 2026-01-15 09:30 UTC, the counter is zero, and the status reads Preparing interaction. useId produces a label association when the tree and root prefix match; it is not a list key. The readiness label changes only after the client Effect runs. Effects do not run on the server. utcLabel expects valid ISO input from the trusted fixture; validate real inputs separately. The serialization helper emits JSON while escaping less-than signs so the data cannot close its script element. Do not serialize secrets.
Build matching HTML and hydrate the same container
import React from 'react';import {renderToString} from 'react-dom/server';import {Garden,initial,serializeInitial} from './c39-l02-s03.jsx';export function htmlDocument(){ const body=renderToString(<Garden data={initial}/>,{identifierPrefix:'garden-'}); return '<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Garden</title></head><body><div id="root">'+body+'</div><script type="application/json" id="initial-data">'+serializeInitial(initial)+'</script><script type="module" src="./client.js"></script></body></html>';}The server wraps the React fragment in a document and provides an inert JSON snapshot. The client.js URL is a proposed local build artifact, not a dependency that already exists. The fixture uses only synthetic public values. The JSON serialization helper prevents a literal closing script tag in the snapshot, while React escapes normal text nodes itself. Do not concatenate arbitrary HTML or untrusted script URLs. Build instructions and verification are in the chapter fixture README.
import React from 'react';import {hydrateRoot} from 'react-dom/client';import {Garden} from './c39-l02-s03.jsx';const host=document.getElementById('root');const snapshot=document.getElementById('initial-data');if(!host||!snapshot)throw new Error('Missing hydration fixture');const data=JSON.parse(snapshot.textContent);hydrateRoot(host,<Garden data={data}/>,{identifierPrefix:'garden-',onRecoverableError(error){console.error('Hydration fixture:',error.message);}});The first browser render reuses the same data and identifierPrefix. After hydration, clicking the native button should increment the count; the label should focus its input. The client does not replace the root with createRoot, which is for a client-rendered root. Do not call root.render before hydration completes, because that can discard the server markup. Treat mismatches as bugs rather than assuming React will repair every attribute. onRecoverableError is a useful reporting hook, not proof of success: also inspect console diagnostics, markup and interaction. Avoid logging private data in production. Practice: change the server and client prefixes in a disposable copy, observe the warning, and restore the shared prefix.