What is hydration and what causes hydration errors?
Hint
Attaching React event listeners to server-rendered HTML — mismatch between server and client render causes errors
Full Answer
Hydration is the process of React attaching event listeners and state to server-rendered HTML. React "expects" the client render to produce identical HTML to what the server sent.
Common causes of hydration mismatch:
// ❌ Browser-only APIs in render
function Component() {
return <div>{window.innerWidth}</div>; // window doesn't exist on server!
}
// ❌ Rendering different content for logged-in users
function Greeting() {
return <p>Hello {localStorage.getItem('name')}</p>; // localStorage = server-undefined
}
// ❌ Time/random values
function Card() {
return <p>Generated at: {new Date().toISOString()}</p>; // different each render
}
function Avatar() {
return <img src={`https://api/avatar?${Math.random()}`} />; // different random
}
Fixes:
// ✅ useEffect for browser-only values (runs client-side only)
function Component() {
const [width, setWidth] = useState(0);
useEffect(() => { setWidth(window.innerWidth); }, []);
return <div>{width}</div>;
}
// ✅ suppressHydrationWarning for expected mismatches (timestamps)
<time suppressHydrationWarning>{new Date().toISOString()}</time>
💡 The suppressHydrationWarning prop should be used sparingly — it hides real errors. Fix the root cause wherever possible.
More Server Components Questions
Practice this in a timed sprint
5 free questions, no signup required