Sub topic 2
Common Causes of Hydration Mismatches
Assume you know React function components, hooks, JSX, and basic browser DOM behavior. A hydration mismatch occurs when the HTML React rendered on the server differs from the output of the first client render. React may discard server HTML for that part and render again in the browser.
Common causes of mismatches
Common causes include:
- Current time or dates, because the server and browser run at different moments.
- Random values, such as
Math.random(). - Browser-only checks, such as reading
window,localStorage, ornavigator. - Different data arriving on the server and client.
- Invalid HTML nesting. The browser may repair invalid markup before React hydrates it.
Fixing mismatches with client-only effects
Render the same stable placeholder on both sides. Read browser-only or time-dependent values after hydration in an effect.
import { useEffect, useState } from 'react';
export default function Clock() {
const [time, setTime] = useState('');
useEffect(() => {
setTime(new Date().toLocaleTimeString());
}, []);
return <p>{time}</p>;
}The initial output is an empty paragraph on both server and client. The effect runs only in the browser and updates it afterward.
Matching IDs with `useId`
Do not create accessibility IDs with counters or random values. useId generates an identifier that matches during server rendering and hydration.
import { useId } from 'react';
function EmailField() {
const id = useId();
return <><label htmlFor={id}>Email</label><input id={id} /></>;
}Browser state with `useSyncExternalStore`
For external browser state, provide a server snapshot. The third argument below makes the server and first client render agree.
import { useSyncExternalStore } from 'react';
function subscribe(fn) {
addEventListener('online', fn);
addEventListener('offline', fn);
return () => {
removeEventListener('online', fn);
removeEventListener('offline', fn);
};
}
export function useOnline() {
return useSyncExternalStore(subscribe, () => navigator.onLine, () => true);
}`suppressHydrationWarning`
Use suppressHydrationWarning only for a small, intentional text or attribute difference, such as a timestamp. It hides a warning; it does not repair incorrect structure or event behavior.
Suspense boundaries as streaming units
A Suspense boundary separates content that can arrive later. Streaming SSR can send the page shell and fallback first, then send the completed boundary. The boundary can hydrate independently when its code and data are ready.
Exercise
Why should a clock read the time in an effect instead of during render?
Show answer
The server and browser would otherwise calculate different values during their first renders.