Sub topic 16
A Workflow for Debugging Hydration Errors
Earlier chapters covered what causes hydration mismatches and how to fix each cause. This chapter gives you a repeatable order of steps for finding the cause when you only have an error message and a large component tree. It assumes you can run a streaming SSR setup like the Express example from earlier. It also assumes you know hydrateRoot, useEffect, and Suspense.
Why a workflow helps
A hydration error names a symptom, such as a text difference or an attribute difference. It doesn't always name the component that caused it. The cause can also be far from the symptom. For example, an invalid nesting in a layout can shift the DOM for a whole subtree.
Debugging goes faster when you answer these questions in order:
- Is this really a hydration mismatch?
- What did the server send, and what did the client expect?
- Which component produced the difference?
- Which known cause matches?
- How will I see this error in production?
Step 1: Read the message carefully
Reload the page in development mode. Production builds strip most detail, so don't debug there first. The message usually falls into one of these groups.
| Message pattern | What it usually means |
|---|---|
| Text content does not match server-rendered HTML | Text differs, often from time, locale, or random values |
| Prop `id` did not match (or another attribute) | An attribute differs, often a generated id or a class built from a browser check |
| Expected server HTML to contain a matching element | The client rendered a node the server did not send |
| Hydration failed because the initial UI does not match | The tree differs. This is the general form |
| `validateDOMNesting` warning | Invalid element nesting, such as a `div` inside a `p` |
Newer React versions print a diff that marks the server value and the client value. Copy both values. They are your best clue, because they often show the cause directly. A timestamp that differs by a second, or a 0.7381 next to a 0.1204, points straight at time or randomness.
Step 2: Look at the raw server HTML
The Elements panel in browser DevTools shows the DOM after the browser has parsed, repaired, and changed it. That isn't what the server sent. To see the real server output, fetch it without running any client code.
curl -s http://localhost:3000/ | head -c 2000You can also use "View page source" in the browser. Compare it with what the client renders. Look for these things:
- A
<p>that closes early because it contained a block element. - A table with no
<tbody>. The browser inserts one, but the server HTML doesn't have it. - Text that is missing, or that has different spacing.
- A value, such as a date, that is already formatted for the server's locale and time zone.
If the HTML was changed after it left your server, suspect the infrastructure. Proxies, CDNs, and HTML minifiers can rewrite markup or inject scripts. Browser extensions can also modify the DOM before React hydrates it. Test in a private window with extensions off to rule that out.
Step 3: Bisect the tree
When the diff doesn't identify the component, remove suspects from the server render. A small helper renders nothing until the component has mounted in the browser.
import { useEffect, useState } from 'react';
export function ClientOnly({ children }) {
const [mounted, setMounted] = useState(false);
useEffect(() => {
setMounted(true);
}, []);
return mounted ? children : null;
}Wrap half of the suspect subtree and reload.
export default function Page() {
return (
<main>
<Header />
<ClientOnly>
<Sidebar />
<Feed />
</ClientOnly>
</main>
);
}- If the error disappears, the cause is inside the wrapped half. Wrap smaller parts of it and repeat.
- If the error remains, the cause is in the unwrapped part. Move the wrapper there.
Within a few rounds you reach a single component. This is a diagnostic tool. The wrapped content leaves the server HTML, so you lose its SEO and first-paint benefits. Once you know the cause, remove the wrapper and apply a proper fix.
Also read the component stack in the error, when it is present. It lists the components between the failing node and the root, which narrows the search before you bisect.
Step 4: Match the cause and fix it
With the component found, read its render code for values that differ between server and browser.
| What you find | Fix |
|---|---|
| `new Date()`, `Date.now()`, locale or time zone formatting during render | Render a placeholder, then set the value in `useEffect` |
| `Math.random()`, counters, or generated ids | Use `useId` |
| `window`, `localStorage`, `navigator`, or `typeof window` checks in render | Use `useSyncExternalStore` with a `getServerSnapshot`, or move the read into an effect |
| Invalid nesting such as `div` in `p`, or a link inside a link | Use valid nesting |
| Data that differs between server and client fetches | Pass the server data to the client, or fetch inside a Suspense boundary |
Here is a typical bug. A greeting depends on the browser's time zone, so the server and client disagree.
import { useEffect, useState } from 'react';
// Mismatch: the server's time zone and the browser's time zone can differ.
function BadGreeting() {
const hour = new Date().getHours();
return <p>{hour < 12 ? 'Good morning' : 'Good afternoon'}</p>;
}
// Fix: both sides render the same neutral text first.
function Greeting() {
const [text, setText] = useState('Hello');
useEffect(() => {
const hour = new Date().getHours();
setText(hour < 12 ? 'Good morning' : 'Good afternoon');
}, []);
return <p>{text}</p>;
}The neutral text keeps the first client render identical to the server HTML. The effect then updates it after hydration.
Step 5: Confirm the fix
Reload and check three things. The console shows no hydration warning. The raw HTML from curl still contains the content you expect. The page works when you navigate to it directly and when you reload it, because the client-side and server-side paths can differ.
Step 6: See errors in production
A mismatch in production often doesn't break the page, because React recovers by client rendering. Inside a Suspense boundary, only that boundary is re-rendered on the client. Outside one, the whole root is. You lose the performance benefit without any visible failure. Log these events so you notice them.
import { hydrateRoot } from 'react-dom/client';
import App from './App.js';
hydrateRoot(document, <App />, {
onRecoverableError(error, errorInfo) {
const payload = JSON.stringify({
message: String(error && error.message),
componentStack: errorInfo && errorInfo.componentStack,
url: window.location.href
});
navigator.sendBeacon('/log/hydration', payload);
}
});Group the reports by message and component stack. A mismatch that appears only for some users often comes from locale, time zone, or browser extensions. That is a clue you can't get from local testing.
Edge cases to keep in mind
- Errors that reproduce only sometimes. Time-based values mismatch only when the second changes between the server render and hydration. Random values mismatch every time, so a flaky error points at time.
- Errors inside streamed boundaries. The server HTML for a boundary arrives later, and the client may hydrate it separately. Check the Suspense boundary named in the component stack, and not only the shell.
- Third-party components. If a library component fails, wrap it in
ClientOnlyor load it withlazyinside a Suspense boundary. Then report the issue to the library. - Server errors versus mismatches. A failure in
onShellErrororonErrorhappens on the server and shows in server logs. A mismatch appears in the browser console. Don't search the wrong side.
Exercise
Your console shows "Text content does not match server-rendered HTML." The diff shows the server text as "10:04:26 AM" and the client text as "10:04:27 AM". The page is built from about 40 components and you don't know which one renders the time. Describe the steps you take to find and fix it.
Show answer
Read the diff first. Two values that differ by a second point to a time value formatted during render. Run curl on the page to confirm the server HTML contains "10:04:26 AM". Then bisect: wrap half of the suspect subtree in ClientOnly and reload, and keep narrowing until the error disappears and you reach one component. In that component, replace the render-time call to new Date() with state that starts as a neutral placeholder (an empty string) and set the real time in useEffect. Remove the ClientOnly wrappers, reload, and confirm the console is clean. Finally, add onRecoverableError to hydrateRoot to log any mismatch that appears in production.