Sub topic 6
Common causes of mismatches
This chapter assumes you know function components, useState and useEffect, basic HTML and the DOM, and how hydrateRoot attaches React to server HTML. It covers what makes the first client render differ from the server HTML. The next chapters cover the fixes in detail.
The rule behind every mismatch
During hydration, React renders your components in the browser and compares the result with the HTML already on the page. It expects both to describe the same tree. A mismatch happens when they differ.
Hydration does not repair attribute differences, so the rule is strict. Your render must be a pure function of props, state, and context. Anything else that feeds into the output can differ between the server and the browser. That includes the clock, random numbers, window, locale, time zone, and the HTML parser itself.
The causes below fall into a few groups.
| Cause | Why the output differs | Typical fix |
|---|---|---|
| Current time | The server and the browser read the clock at different moments | Render the value in an effect |
| Time zone and locale | The server and the browser format dates differently | Format in an effect, or pass explicit options |
| `Math.random()` or counters | Each side generates a different value | `useId` for ids, or generate in an effect |
| `typeof window` checks | The server takes one branch, the browser the other | Effect or `useSyncExternalStore` |
| Browser-only state | `localStorage` and `navigator` do not exist on the server | Effect or `useSyncExternalStore` |
| Invalid HTML nesting | The browser parser rewrites the DOM before hydration | Fix the nesting |
| Different data | The server and the client render with different data | Pass the same data to both |
| Extensions or CDN rewriting | Something changes the HTML between server and React | Check the raw response |
Time and other changing values
The most common cause is reading a value that changes. A clock is the classic case.
import { useEffect, useState } from 'react';
// Causes a mismatch: the server and the browser compute different text.
function BadClock() {
return <p>{new Date().toLocaleTimeString()}</p>;
}
// Fix: render the same placeholder on both, then fill in the time after hydration.
function Clock() {
const [now, setNow] = useState(null);
useEffect(() => {
setNow(new Date());
}, []);
return <p>{now ? now.toLocaleTimeString() : ''}</p>;
}BadClock fails for two reasons. The server rendered the page at one moment and the browser hydrates it later. Also, toLocaleTimeString() with no arguments uses the runtime's locale and time zone. A server in UTC and a browser in another zone produce different text even if the moments were identical.
Effects do not run on the server, and they run only after hydration finishes. So the first client render uses the null state, matching the server output. The effect then triggers a second render that shows the time.
The same reasoning applies to Math.random(), Date.now(), crypto.randomUUID(), and module-level counters. Each produces a different value on each side.
Branching on the environment
A second group of bugs comes from code that checks where it runs.
function Greeting() {
// Mismatch: the server takes the first branch, the browser the second.
if (typeof window === 'undefined') {
return <p>Welcome</p>;
}
return <p>Welcome back</p>;
}This looks harmless, but the browser's first render takes the window branch while the server HTML contains the other text. React reports a text mismatch.
Reading localStorage, navigator.userAgent, window.innerWidth, or matchMedia during render has the same effect. On the server these either throw or return nothing useful, and in the browser they return real values.
There are two usual fixes. For a value you read once, move it into an effect, as with the clock. For a value that changes over time and that you subscribe to, use useSyncExternalStore with a server snapshot:
import { useSyncExternalStore } from 'react';
function subscribe(callback) {
window.addEventListener('online', callback);
window.addEventListener('offline', callback);
return () => {
window.removeEventListener('online', callback);
window.removeEventListener('offline', callback);
};
}
function useOnlineStatus() {
return useSyncExternalStore(
subscribe,
() => navigator.onLine,
() => true
);
}The third argument is getServerSnapshot. React uses it on the server and during hydration, so both sides start with true. After hydration React switches to the real navigator.onLine value.
Invalid HTML nesting
Some mismatches have nothing to do with your values. The server sends a string of HTML, and the browser parses it into DOM nodes. When the string breaks HTML nesting rules, the parser rewrites the structure.
function Bad() {
// A div inside a p is invalid HTML, so the browser's parser restructures the DOM
// and the tree React expects no longer matches what it finds.
return (
<p>
<div>Details</div>
</p>
);
}
function Good() {
return (
<div>
<div>Details</div>
</div>
);
}A <p> cannot contain a <div>. When the parser meets the <div>, it closes the <p> first. The resulting DOM has an empty paragraph and a sibling div, but React expects the div inside the paragraph.
Other common offenders:
- A
<div>or<p>inside a<p>. - An
<a>inside another<a>. - A
<tr>placed directly in a<table>, with no<tbody>, in hand-written HTML. React's own output is usually fine, but wrapping elements around table parts can break it. - A
<button>inside another<button>.
React's development build warns about many invalid nestings. Read those warnings first, because the fix is usually a one-line change of the outer tag.
Ids that differ between sides
Generating ids with a counter or random number gives different values on each side. Labels and inputs then point at ids that do not match the server HTML. useId solves this because it produces the same id on the server and in the browser for the same position in the tree.
import { useId } from 'react';
function EmailField() {
const id = useId();
return (
<>
<label htmlFor={id}>Email</label>
<input id={id} type="email" />
</>
);
}Call useId once per component and derive related ids from it, for example ` ${id}-hint `.
Data that differs between sides
A subtler cause is rendering with different data. The server may render with data it fetched, while the client starts with an empty cache or a different user state. If the first client render shows a loading state and the server HTML shows content, they differ.
The server and client must begin from the same data. Typically you serialize the server's data into the page and pass it as the initial value on the client. The exact mechanism depends on your data library, and a later chapter covers how Suspense changes this.
Things outside your code
Occasionally your code is correct and the HTML still changes before React sees it.
- Browser extensions can inject elements or attributes into the page.
- Some CDNs or proxies minify or rewrite HTML, for example by stripping comments or whitespace.
- Whitespace differences in hand-assembled HTML templates.
To check, look at the raw response with curl or the Network tab, not at the Elements panel. The Elements panel shows the DOM after the parser and any extensions have run. If the raw HTML is what your server produced, the problem is on the client side.
A quick triage checklist
When you see a mismatch error, ask these questions in order:
- Does the component read the time, a random value, or a counter during render?
- Does it branch on
typeof window, or read browser-only APIs during render? - Does it format dates or numbers using the default locale or time zone?
- Is the HTML nesting valid?
- Do the server and the first client render receive the same data?
- Does the raw server response match what your server code generates?
Exercise
A component renders <p>{window.innerWidth > 600 ? 'Wide' : 'Narrow'}</p>. The page loads with a hydration warning. Explain why, and name one way to fix it.
Show answer
On the server window does not exist, so the render either throws or takes a different path than the browser. In the browser the first render computes a real width and may produce text that differs from the server HTML. Fix it by rendering a fixed placeholder on both sides and reading window.innerWidth in an effect, or by using useSyncExternalStore with a subscription to resize events and a getServerSnapshot that returns a fixed default.
Exercise
A page hydrates without any value-related warnings, but the console shows an error about unexpected DOM structure. The component returns <p><div>Details</div></p>. What happens in the browser, and how do you fix it?
Show answer
The HTML parser closes the <p> when it reaches the <div>, because a div is not allowed inside a p. The resulting DOM differs from the tree React expects, so hydration reports a mismatch. Change the outer element to a div (or the inner one to a span) so the nesting is valid.