Sub topic 5
Hydration mismatches: what they are and what they cost
This chapter assumes you know function components, useState and useEffect, basic HTML and the DOM, and that you have seen hydrateRoot attach React to server-rendered HTML. It covers what a mismatch is and what it costs. Later chapters cover causes and fixes.
What a mismatch is
During hydration, React renders your components in the browser and compares the result with the HTML the server already sent. It expects the two to be the same. A hydration mismatch happens when they differ in element type, attributes, or text.
Here is a component that triggers one:
function BadClock() {
return <p>{new Date().toLocaleTimeString()}</p>;
}The server computes the time when it renders. The browser computes it again, later, often in a different time zone. The text in the HTML and the text React expects are different.
The hydration flow
What it costs
React's response to a mismatch is to recover, not to crash. The recovery has costs.
- Lost work. React discards the server HTML for the affected part of the tree, up to the nearest Suspense boundary, and builds new DOM on the client. This is the work that SSR was meant to save.
- Slower interactivity. The page stays inert for longer because React does extra rendering before it can attach handlers.
- Visible flicker. The user sees the server text, then sees it replaced. Layout can shift, and focus or scroll position inside the replaced area can be lost.
- Hidden bugs. In some cases the text differs but the structure is the same. Treat every mismatch as a bug. React does not promise to patch up attribute differences, so the page can end up with stale or wrong values.
- Noise in logs. In development React prints a warning that names the difference. In production, the error is reported through
onRecoverableError, which you will use in a later chapter.
Where the mismatch comes from
The rule is that the first client render must produce the same output as the server render. Anything that changes between the two breaks it. Typical sources are:
- Values that depend on time or randomness.
- Checks for browser-only objects, such as
window. - Invalid HTML nesting, which the browser repairs before React sees it.
The next chapter looks at each of these in detail.
Exercise
A page server-renders a component that returns <p>{Math.random()}</p>. Hydration reports an error. Why does it happen, and what does the user pay for it?
Show answer
The server and the browser each call Math.random() and get different numbers, so the text in the HTML does not match the first client render. React reports a recoverable error and re-renders the affected part on the client. The user pays with wasted server work, a longer wait before the page is interactive, and a possible visible flicker as the text is replaced.