Next.js Hydration Failed— Fixed [Complete Guide 2026]
Also covers: There was an error while hydrating · Hydration mismatch · suppressHydrationWarning
⚡ Most Common Fix — Move Browser Code Into useEffect
'use client'
import { useState, useEffect } from 'react'
// ❌ WRONG — localStorage read during render causes hydration mismatch
export default function MyComponent() {
const theme = localStorage.getItem('theme') // crashes on server!
return <div>{theme}</div>
}
// ✅ CORRECT — read after mount, server and client render match
export default function MyComponent() {
const [theme, setTheme] = useState(null)
useEffect(() => {
setTheme(localStorage.getItem('theme'))
}, [])
return <div>{theme}</div>
}What Causes Next.js Hydration Failed?
Error: Hydration failed because the initial UI does not match what was rendered on the server.
Warning: Expected server HTML to contain a matching <div> in <div>.
at div
at MyComponent
There was an error while hydrating. Because the error happened outside of a Suspense boundary,
the entire root will switch to client rendering.Next.js renders your pages on the server first (SSR), sending HTML to the browser. React then hydrates that HTML — attaching event listeners and making it interactive. Hydration fails when the HTML React tries to attach to does not match what React would render itself. React cannot reconcile the difference and throws this error.
| Cause | What happens | Fix |
|---|---|---|
| localStorage / window in render | Server throws — client renders fine | Jump → |
| Date / time formatting | Server time ≠ client time | Jump → |
| Math.random() in JSX | Different values each render | Jump → |
| Invalid HTML nesting | Browser auto-corrects → mismatch | Jump → |
| Browser extension injecting attributes | Grammarly, LastPass add DOM attrs | Jump → |
| Conditional render based on window | Server: false, client: true | Jump → |
Invalid HTML Nesting
Browser auto-corrects invalid HTML — React sees different DOMThe browser silently fixes invalid HTML (like <p> inside <p>, or <div> inside <p>). The server sends one structure, the browser corrects it, React tries to hydrate the corrected version — mismatch.
// ❌ WRONG — <div> cannot be a child of <p>
export default function Card({ text }) {
return (
<p>
<div>Some content</div> {/* invalid! browser moves this out */}
{text}
</p>
)
}
// ✅ CORRECT — use valid nesting
export default function Card({ text }) {
return (
<div>
<div>Some content</div>
<p>{text}</p>
</div>
)
}
// Other common invalid patterns:
// <a> inside <a>
// <button> inside <button>
// <ul> / <ol> with non-<li> direct children
// <table> without <tbody> (browser adds it automatically)Run your HTML through the W3C Validator or install the 'axe' accessibility extension — both catch invalid nesting that causes hydration errors.
localStorage / window in Render
Server has no window — most common causeThe server has no window, localStorage, document, or navigator. Accessing them during render crashes the server render, causing a mismatch.
'use client'
import { useState, useEffect } from 'react'
// ❌ WRONG — crashes on server
export default function ThemeProvider({ children }) {
const saved = localStorage.getItem('theme') || 'light' // ReferenceError on server
const [theme, setTheme] = useState(saved)
return <div data-theme={theme}>{children}</div>
}
// ✅ CORRECT — start with null/default, read after mount
export default function ThemeProvider({ children }) {
const [theme, setTheme] = useState('light') // safe default for server
useEffect(() => {
// Only runs on client, after hydration
const saved = localStorage.getItem('theme')
if (saved) setTheme(saved)
}, [])
return <div data-theme={theme}>{children}</div>
}
// ✅ Also correct — typeof check
const isClient = typeof window !== 'undefined'
const saved = isClient ? localStorage.getItem('theme') : 'light'Date and Time Mismatches
Server and client render different timestampsIf you render new Date().toLocaleDateString() or any current time during SSR, the server renders one value and the client renders a different one (even milliseconds later). This is a guaranteed hydration mismatch.
'use client'
import { useState, useEffect } from 'react'
// ❌ WRONG — renders different time on server vs client
export default function Timestamp() {
return <span>{new Date().toLocaleTimeString()}</span>
}
// ✅ CORRECT — render placeholder on server, real time on client
export default function Timestamp() {
const [time, setTime] = useState(null)
useEffect(() => {
setTime(new Date().toLocaleTimeString())
}, [])
if (!time) return null // or a skeleton
return <span>{time}</span>
}
// ✅ For static dates (build time) — these are consistent
export default function BuildDate() {
// This is fine — renders same value on server and client
return <span>{"Published: 2026-01-15"}</span>
}Math.random() and Dynamic IDs
Different random values on server and client// ❌ WRONG — Math.random() produces different values
export default function Avatar({ name }) {
const id = Math.random().toString(36) // server: 'abc', client: 'xyz' → mismatch
return <div id={id}>{name}</div>
}
// ✅ CORRECT — use React's useId hook (React 18+)
import { useId } from 'react'
export default function Avatar({ name }) {
const id = useId() // same value on server and client
return <div id={id}>{name}</div>
}
// ✅ CORRECT — derive IDs from stable props
export default function Avatar({ name, userId }) {
return <div id={`avatar-${userId}`}>{name}</div>
}React 18's useId() hook is specifically designed for this — it generates stable IDs that match between server and client renders.
suppressHydrationWarning
For intentional mismatches onlySome elements legitimately differ between server and client — like timestamps or user-specific content. Use suppressHydrationWarning to tell React to ignore the mismatch for that specific element.
// suppressHydrationWarning only applies to the element it is on
// and its direct text content — NOT its children
export default function LiveClock() {
return (
<time suppressHydrationWarning>
{new Date().toLocaleTimeString()}
</time>
)
}
// ❌ DO NOT use this as a blanket fix
// <body suppressHydrationWarning> ← this silences ALL hydration errors
// Only use on specific elements where the mismatch is intentionalsuppressHydrationWarning does not fix the underlying problem — it just silences the warning. If the mismatch causes wrong content to be shown to users, they will see it even with the warning suppressed.
useEffect for Client-Only Content
Conditional rendering based on browser APIsA very common pattern: showing different content based on whether the user is logged in, what OS they are on, or any other browser-detected value. The server always renders the default state.
'use client'
import { useState, useEffect } from 'react'
// Reusable wrapper — renders nothing on server, children on client
export function ClientOnly({ children, fallback = null }) {
const [mounted, setMounted] = useState(false)
useEffect(() => setMounted(true), [])
return mounted ? children : fallback
}
// Usage
import { ClientOnly } from './ClientOnly'
export default function Page() {
return (
<div>
<h1>My Page</h1>
<ClientOnly fallback={<p>Loading...</p>}>
{/* This only renders on client — no hydration mismatch */}
<UserDashboard />
</ClientOnly>
</div>
)
}Browser Extensions Causing Mismatch
Grammarly, LastPass, Honey, ad blockersBrowser extensions inject attributes and elements into the DOM after the page loads. Grammarly adds data-lt-installed, password managers add attributes to forms, ad blockers remove elements. React sees a different DOM than what it rendered.
// Suppress on body for extension-injected attributes
export default function RootLayout({ children }) {
return (
<html lang="en">
<body suppressHydrationWarning>
{children}
</body>
</html>
)
}
// Test in private/incognito window with extensions disabled
// If hydration error disappears → extension is the causeAlways test hydration errors in a private browser window with no extensions. If the error disappears, add suppressHydrationWarning to the body — this is a legitimate use case.
Third-Party Scripts Modifying the DOM
Analytics, chat widgets, A/B testing scriptsScripts like Google Analytics, Intercom, and Optimizely modify the DOM after load. Load them using Next.js Script component with the correct strategy so they do not interfere with hydration.
import Script from 'next/script'
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
{children}
{/* afterInteractive — runs after hydration completes */}
<Script
src="https://www.googletagmanager.com/gtag/js?id=GA_ID"
strategy="afterInteractive"
/>
{/* lazyOnload — runs when browser is idle */}
<Script
src="https://widget.intercom.io/widget/APP_ID"
strategy="lazyOnload"
/>
</body>
</html>
)
}How to Prevent Hydration Errors
- Never access window, localStorage, document, or navigator during render — always use useEffect
- Use React 18's useId() for dynamic IDs instead of Math.random()
- Keep date/time rendering client-side only — initialize state to null and set in useEffect
- Validate HTML nesting — <div> inside <p> is invalid and causes browser corrections
- Test in a private browser window with no extensions during development
- Load third-party scripts with strategy='afterInteractive' or 'lazyOnload'
- Use suppressHydrationWarning only for genuinely intentional mismatches
Frequently Asked Questions
What causes Next.js hydration failed error?+−
How do I fix hydration error in Next.js?+−
Next.js hydration error in production but not development?+−
Can I use suppressHydrationWarning to fix hydration errors?+−
Hydration error caused by browser extension — how to fix?+−
How do I find which component is causing hydration error?+−
Need Expert Help?
We Build Production-Grade Next.js Apps
Softplix builds full-stack Next.js applications. Dealing with hydration errors or SSR issues in production? We can help.
Talk to an Engineer