Sub topic 7
Fixing Mismatches with Client-Only Effects
This chapter assumes you can write function components with useState and useEffect. It also assumes you have a working server setup with renderToPipeableStream and a client entry that calls hydrateRoot. You should already know that a hydration mismatch means the browser's first render differs from the HTML the server sent. Here you fix the most common kind: values that only the browser can know.
Why effects solve the problem
Hydration works only if the first client render produces the same output as the server HTML. React then reuses the existing DOM and attaches event handlers instead of rebuilding anything.
Effects fit this rule because of when they run:
- Effects never run on the server.
renderToPipeableStreamrenders components but skipsuseEffect. - On the client, effects run after React has hydrated and committed the tree.
- A state update inside an effect triggers a normal re-render. React does not compare that render against the server HTML, so it can't produce a mismatch.
Anything you compute inside an effect is therefore client-only by construction. The server and the first client render both see the initial state. The real value arrives afterward.
A mismatch in practice
Time is the standard example.
function BadClock() {
return <p>{new Date().toLocaleTimeString()}</p>;
}The server renders this at one moment, in the server's time zone and locale. The browser hydrates later, possibly in another time zone. The two strings differ, so React reports a mismatch. In development you get a warning. In production React may discard the server HTML for that part of the tree and render it again on the client, which wastes the work the server did.
Math.random(), Date.now(), window.innerWidth, and localStorage values cause the same problem. Each one gives the server and the browser different answers.
The two-pass render
The fix is to render a neutral placeholder on both sides, then fill in the real value after hydration.
import { useEffect, useState } from 'react';
export default function Clock() {
const [now, setNow] = useState(null);
useEffect(() => {
setNow(new Date());
}, []);
return <p>{now ? now.toLocaleTimeString() : ''}</p>;
}The sequence is:
- On the server,
nowisnull, so the output is an empty<p></p>. - In the browser's first render,
nowis alsonull, so React finds identical markup and hydrates cleanly. - After hydration, the effect runs and calls
setNow. React re-renders with the real time.
A live clock
A clock that ticks needs an interval. Clean it up in the effect's return function. In development, Strict Mode runs effects twice, and a missing cleanup would leave two timers running.
import { useEffect, useState } from 'react';
export default function LiveClock() {
const [now, setNow] = useState(null);
useEffect(() => {
setNow(new Date());
const id = setInterval(() => setNow(new Date()), 1000);
return () => clearInterval(id);
}, []);
return <p>{now ? now.toLocaleTimeString() : '--:--:--'}</p>;
}The placeholder --:--:-- has roughly the same width as a real time. This keeps the layout from shifting when the value appears.
A reusable hook for client-only values
Many components need the same "am I in the browser yet?" signal. Put it in a hook.
import { useEffect, useState } from 'react';
function useIsClient() {
const [isClient, setIsClient] = useState(false);
useEffect(() => {
setIsClient(true);
}, []);
return isClient;
}
export default function ThemeLabel() {
const isClient = useIsClient();
const theme = isClient ? localStorage.getItem('theme') ?? 'light' : 'light';
return <p>Theme: {theme}</p>;
}On the server and in the first client render, isClient is false, so both show light. After hydration the component re-renders with the stored theme. The localStorage call only runs once isClient is true, so it never executes on the server, where localStorage does not exist.
A check that looks right but fails
A tempting shortcut is to test whether window exists.
function Where() {
const isBrowser = typeof window !== 'undefined';
return <p>{isBrowser ? 'browser' : 'server'}</p>;
}Choosing the right tool
An effect is not the only fix. Pick the tool that matches the source of the difference.
| Source of the difference | Fix | Covered in |
|---|---|---|
| Time, randomness, `localStorage`, viewport size | Placeholder, then an effect | This chapter |
| Element ids that must pair up (`label` and `input`) | `useId` | Stable ids chapter |
| Browser state you subscribe to, such as online status | `useSyncExternalStore` with a server snapshot | External store chapter |
| One unavoidable text difference, such as a timestamp | `suppressHydrationWarning` | Suppress-warning chapter |
| Invalid HTML nesting | Correct the markup | Common causes chapter |
Trade-offs and edge cases
The two-pass pattern is simple, but it has costs.
- The server HTML is incomplete. Search crawlers and users with JavaScript disabled see the placeholder. Don't hide important content such as article text or prices behind an effect.
- The user sees a change. The page paints first with the placeholder and updates a moment later. Reserve space with a similar-sized placeholder, or give the container a fixed
min-height. - Each use costs one extra render. This is cheap for a clock or a label. It is not cheap if you wrap your whole app in a client-only gate, because you would lose the point of server rendering.
- Third-party widgets may touch
windowat import or render time. Wrap only that widget in a component that rendersnulluntiluseIsClient()returnstrue. The rest of the page still benefits from SSR. - Cleanup is your job. Intervals, subscriptions, and listeners started in the effect must be removed in the cleanup function.
- Don't read browser values in state initializers. Code such as
useState(window.innerWidth)runs during render. It crashes on the server and mismatches on the client. Start from a fixed default and set the real value in an effect.
If a mismatch persists after you apply this pattern, look for a second cause. Invalid nesting or a value read in another component can produce the same warning, and the debugging chapter covers how to find it.
Exercise
A component renders <p>Window width: {window.innerWidth}px</p>. It crashes during server rendering. A teammate "fixes" it with typeof window !== 'undefined' ? window.innerWidth : 0, and now the server succeeds but React logs a hydration mismatch in the browser. Explain why the mismatch appears, then rewrite the component so it neither crashes nor mismatches.
Show answer
On the server the check is false, so the HTML contains 0. In the browser the first render runs the check as true and produces the real width, such as 1280. The two outputs differ, so hydration reports a mismatch. The fix is to start with the same value on both sides and read the width in an effect:
import { useEffect, useState } from 'react';
export default function WindowWidth() {
const [width, setWidth] = useState(0);
useEffect(() => {
const update = () => setWidth(window.innerWidth);
update();
window.addEventListener('resize', update);
return () => window.removeEventListener('resize', update);
}, []);
return <p>Window width: {width}px</p>;
}
The server and the first client render both output 0. After hydration the effect sets the real width and keeps it updated, and the cleanup removes the listener.