“Hydration failed because the server rendered HTML didn’t match the client”: causes and fixes
Error message: Hydration failed because the server rendered HTML didn't match the client
With server rendering, React renders your component twice: once on the server to produce HTML, and once in the browser to attach event handlers. If the two results differ, you get a hydration error. The fix depends on why they differ.
1. Values that change between server and browser
Date.now(), new Date().toLocaleString() (different time zone and locale), Math.random(), or a random id generated during render.
Fix: render a stable value first, then update it in the browser:
"use client";
import { useEffect, useState } from "react";
export function LocalTime({ iso }: { iso: string }) {
const [text, setText] = useState(iso.slice(0, 10)); // same on server and client
useEffect(() => setText(new Date(iso).toLocaleString()), [iso]);
return <time dateTime={iso}>{text}</time>;
}Use React's useId() for ids instead of random numbers.
2. Browser-only data during render
Reading window, localStorage or navigator, or writing typeof window !== "undefined" ? a : b, inside the render function. The server always takes one branch and the browser takes the other.
Fix: read it in useEffect, or render the component only in the browser:
"use client";
import dynamic from "next/dynamic";
const Map = dynamic(() => import("./Map"), { ssr: false });In the App Router, ssr: false is only allowed inside a Client Component.
3. Invalid HTML nesting
Browsers silently repair invalid HTML, so the browser's DOM no longer matches what React expects. Typical cases:
- a
<div>or another<p>inside a<p> - an
<a>inside an<a>, or a<button>inside a<button> - a
<table>without<tbody>
Fix: change the outer <p> to a <div>, or restructure so interactive elements aren't nested. React's error message usually names the elements involved.
4. Browser extensions
Password managers, translators and grammar checkers add attributes to <html> or <body> before React loads. Test in a private window with extensions off. If the warning disappears, it isn't your code. Many apps add suppressHydrationWarning to <html>. It only silences differences on that one element, not its children.
How to find the culprit fast
- Read the whole error. Recent React versions print a diff of what the server rendered and what the client expected.
- Comment out halves of the page until the error disappears.
- Look for anything time-, random- or browser-dependent near the reported element.