Sub topic 5
Hydration mismatches: what they are and what they cost
This chapter assumes you can write function components with useState and useEffect, know basic HTML and the browser DOM, and have seen the server-rendering flow from the earlier chapters: the server produces HTML, and hydrateRoot attaches React to it in the browser. Here you will learn what a mismatch is, how React reacts to one, and why the cost is more than a console warning.
What hydration expects
Hydration is the step where React walks the HTML that the server already sent and attaches event handlers and state to it. React does not build new DOM nodes during this step. It renders your components in the browser, then compares the result with the DOM that is already on the page.
This only works if both renders agree. React assumes that the first client render of a component produces the same output as the server render did. When that assumption holds, React reuses every node. When it does not, you have a hydration mismatch.
A hydration mismatch is a difference between the HTML the server produced and the tree React produces during the first render in the browser.
Here is the client entry from the earlier chapters:
import { hydrateRoot } from 'react-dom/client';
import App from './App.js';
hydrateRoot(document, <App />);Nothing in this code is wrong. A mismatch comes from the components inside App, which produce different output depending on where they run.
What counts as a mismatch
React checks several kinds of differences. They do not all carry the same weight.
| Kind of difference | Example | How React treats it |
|---|---|---|
| Text content | Server renders `10:04:12`, client renders `10:04:13` | Reports an error and may patch or re-render |
| Element structure | Server HTML has an extra `<div>` the client tree lacks | Reports an error and falls back to client rendering for that part |
| Missing or extra nodes | A component renders `null` on one side only | Reports an error and falls back to client rendering for that part |
| Attribute values | Different `id`, `class`, or `style` values | Reported in development. React does not patch attributes in production, so the stale value can stay |
The last row is the most dangerous. React does not guarantee that it will repair attribute differences. A wrong id or href can survive hydration silently, and it can break things such as label-to-input links or accessibility relationships.
A mismatch in practice
The simplest mismatch is a value that depends on when or where the code runs.
function BadClock() {
return <p>{new Date().toLocaleTimeString()}</p>;
}The server computes the time when it renders. The browser computes it again some milliseconds or seconds later, possibly in a different time zone and locale. The two strings differ, so the paragraph's text content does not match.
The fix is covered in a later chapter. For now, the point is how to recognize the pattern: any render that reads the clock, a random number, window, localStorage, or the user's locale can produce different output on each side.
Invalid HTML nesting is another source, and it is less obvious:
function Bad() {
return (
<p>
<div>Details</div>
</p>
);
}A div is not allowed inside a p. The browser's HTML parser repairs this while it reads the server HTML, usually by closing the p early. React then expects a p containing a div but finds a p followed by a separate div. The server and client components are identical here. The browser's parser is what changes the DOM.
What React does when it finds one
The behavior depends on what React is hydrating and which version you use. The general model for React 18 and later is as follows.
- React renders the component in the browser and compares the result with the existing DOM.
- When it finds a difference it cannot reconcile, it throws an error internally.
- React catches that error and discards the server-rendered DOM for the nearest enclosing Suspense boundary. If there is no boundary, it discards the whole root.
- It renders that part again on the client and creates fresh DOM nodes.
- It reports the original error to
onRecoverableError.
This is why the error is called recoverable. The page still ends up correct, because the client render is the source of truth. What you lose is the benefit of server rendering for the affected part.
What a mismatch costs
A mismatch rarely breaks the page outright, so its costs are easy to overlook. They fall into four groups.
Performance
Server rendering exists so that users see content early and the browser does little work. When React discards server HTML and renders on the client, the server work for that region was wasted. The browser also has to build the DOM from scratch.
If the mismatch is at the root, for instance because of a difference in <html> or <body>, the whole page falls back to client rendering. You then pay for server rendering and client rendering together, which is slower than choosing either one.
Visible flicker and layout shift
The user first sees the server HTML. When React replaces it, the content can change or move. Text may jump, images may reload, and scroll position or focus inside the replaced region can reset. A form field the user has already started typing in can lose its contents.
Correctness and accessibility
In production, React may leave attribute mismatches as they are, as noted in the table above. A text mismatch may also be patched in place instead of re-rendered, which leaves your event handlers attached to a DOM whose content you did not expect. This can produce subtle bugs, such as a label that points to the wrong input.
Hidden problems in production
In development, React prints a descriptive warning. In production the message is shorter, and without onRecoverableError you may see nothing at all. A page can fall back to client rendering on every request while your dashboards show no failures. Only slower page loads hint at it.
Where the error shows up
During development, the browser console shows a message such as "Hydration failed because the server rendered HTML didn't match the client." Newer React versions include a diff of the expected and actual markup and a component stack. Older versions print a shorter message that names only the element types that differed.
In production, you need to collect these errors yourself:
import { hydrateRoot } from 'react-dom/client';
import App from './App.js';
hydrateRoot(document, <App />, {
onRecoverableError(error, errorInfo) {
console.error('Recoverable error:', error);
console.error('Component stack:', errorInfo.componentStack);
}
});onRecoverableError receives errors that React handled by itself. In a real application, send them to your monitoring service instead of the console. A later chapter treats this callback in more detail.
What does not count
Not every difference between server and browser is a mismatch.
- State changes after hydration. React compares only the first client render. Anything that happens later, such as data loaded in an effect, is a normal update.
- Browser extensions that edit the page. They can change the DOM before React hydrates, and this produces real errors that you cannot fix in your code. Test in a clean browser profile before you debug your components.
- Effects.
useEffectdoes not run during server rendering and runs only after hydration finishes, so it cannot cause a mismatch by itself. This property is what makes effects the standard tool for client-only values.
Common mistakes
- Assuming that identical component code means identical output. The environment changes the output: time, locale,
window, and the browser parser all differ between the two sides. - Checking
typeof window !== 'undefined'during render and returning different markup. The server takes one branch and the browser takes the other, which creates a mismatch by design. - Debugging only in production. The minified messages hide the element and component involved. Reproduce the problem in development first.
- Treating a clean page as proof that hydration worked. The page can look right while React has discarded the server HTML.
Exercise
A component renders <p>{Math.random()}</p>. The page looks correct in the browser after loading, and no errors appear in your production monitoring. Give two reasons why you should still treat this as a problem, and name the callback that would reveal it.
Show answer
The server and the client generate different random numbers, so the first client render does not match the server HTML. React discards the server HTML for that part of the tree and renders it again on the client, which wastes the server work and can cause flicker. A text mismatch may also be patched in place, leaving the page inconsistent. The page looks fine because the client render becomes the source of truth. Production monitoring shows nothing because React recovers silently. Passing onRecoverableError to hydrateRoot reveals the error.
Exercise
A page renders <p><div>Details</div></p> from identical server and client code, yet hydration reports a mismatch. Explain where the difference comes from.
Show answer
The browser's HTML parser treats a div inside a p as invalid and restructures the DOM, typically by closing the p early. By the time React hydrates, the DOM no longer has the structure that the component describes, so the tree React expects differs from the tree it finds. The fix is to use valid nesting, such as a div containing a div.