How to Fix: Hydration failed because the initial UI does not match what was rendered on the server.
A mismatch between Server-Side Rendering (SSR) and Client-Side Rendering (CSR).
What Causes It?
This error occurs when the HTML generated by the Next.js server differs from the HTML React expects when it boots up in the browser. Common culprits include using `window` or `document` directly in the render cycle, relying on `Math.random()`, or invalid HTML nesting (like putting a `<div>` inside a `<p>`).
Plain English Explanation
"Imagine a baker (the server) bakes a cake, and hands it to a decorator (the browser). If the decorator expects a round cake but receives a square one, they panic. React panics ('Hydration failed') when the initial HTML from the server doesn't match what it calculated."
Code Examples
// This will cause a hydration error because Date.now()
// is different on the server vs the client milliseconds later.
export default function Timestamp() {
return <div>Current Time: {Date.now()}</div>;
}// Use useEffect so the dynamic data only renders on the client
import { useState, useEffect } from 'react';
export default function Timestamp() {
const [time, setTime] = useState("");
useEffect(() => {
setTime(Date.now().toString());
}, []);
return <div>Current Time: {time}</div>;
}Step-by-Step Fix
- 1
Check your browser console for the specific element that mismatched (e.g., 'Expected server HTML to contain a matching <div> in <p>').
- 2
Ensure you are not nesting block-level elements (like <div>) inside inline elements (like <p> or <span>).
- 3
If you are using data that changes per render (like dates or random numbers), move that logic inside a `useEffect` hook so it only runs on the client.
- 4
If you are conditionally rendering based on `window.innerWidth`, defer rendering that component until the component has mounted.
Prevention Tips
- Never use `window`, `localStorage`, or `document` directly in the component body.
- Validate your HTML structure using a linter.
- Use custom hooks like `useIsMounted()` to conditionally render client-only components.
FAQs & Interview Prep
Why Interviewers Ask About This
Highly relevant. Interviewers frequently ask 'What is React Hydration?' to test your understanding of Server-Side Rendering (SSR) in frameworks like Next.js.
Can I just suppress the hydration warning?
Yes, you can add `suppressHydrationWarning={true}` to a specific HTML element, but this should only be used as a last resort (e.g., for third-party scripts). It is better to fix the root cause.
Does this affect SEO?
If hydration fails severely, React might fall back to client-side rendering the entire page, which can heavily degrade performance and negatively impact SEO.