Next.jsReactError Fix2026 Updated

Next.js Hydration Failed— Fixed [Complete Guide 2026]

Also covers: There was an error while hydrating · Hydration mismatch · suppressHydrationWarning

January 20267 min readNext.js 13 · 14 · 15 · App Router

⚡ Most Common Fix — Move Browser Code Into useEffect

components/MyComponent.jsx
'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?

Browser Error
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.

CauseWhat happensFix
localStorage / window in renderServer throws — client renders fineJump →
Date / time formattingServer time ≠ client timeJump →
Math.random() in JSXDifferent values each renderJump →
Invalid HTML nestingBrowser auto-corrects → mismatchJump →
Browser extension injecting attributesGrammarly, LastPass add DOM attrsJump →
Conditional render based on windowServer: false, client: trueJump →
1

Invalid HTML Nesting

Browser auto-corrects invalid HTML — React sees different DOM
2 min

The 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.

components/Card.jsx
// ❌ 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.

2

localStorage / window in Render

Server has no window — most common cause
3 min

The server has no window, localStorage, document, or navigator. Accessing them during render crashes the server render, causing a mismatch.

components/ThemeProvider.jsx
'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'
3

Date and Time Mismatches

Server and client render different timestamps
2 min

If 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.

components/Timestamp.jsx
'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>
}
4

Math.random() and Dynamic IDs

Different random values on server and client
1 min
components/UniqueId.jsx
// ❌ 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.

5

suppressHydrationWarning

For intentional mismatches only
1 min

Some 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.

components/LiveClock.jsx
// 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 intentional

suppressHydrationWarning 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.

6

useEffect for Client-Only Content

Conditional rendering based on browser APIs
3 min

A 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.

components/ClientOnly.jsx
'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>
  )
}
7

Browser Extensions Causing Mismatch

Grammarly, LastPass, Honey, ad blockers
1 min

Browser 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.

app/layout.jsx
// 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 cause

Always 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.

8

Third-Party Scripts Modifying the DOM

Analytics, chat widgets, A/B testing scripts
2 min

Scripts 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.

app/layout.jsx
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

Frequently Asked Questions

What causes Next.js hydration failed error?+
Hydration fails when the HTML generated by the server during SSR does not match what React renders on the client. Common causes: accessing browser-only APIs (window, localStorage) during render, date/time differences, invalid HTML nesting, Math.random() in JSX, or browser extensions modifying the DOM.
How do I fix hydration error in Next.js?+
Find the component causing the mismatch. Common fixes: move browser-only code (localStorage, window) into useEffect, use suppressHydrationWarning on elements that intentionally differ, or wrap client-only content in a component that only renders after mount.
Next.js hydration error in production but not development?+
Development mode shows warnings; production mode throws errors. The underlying cause is the same — server/client HTML mismatch. Check for timezone-sensitive date formatting, conditional rendering based on browser detection, or any code path that differs between server and client.
Can I use suppressHydrationWarning to fix hydration errors?+
Only for intentional mismatches where you know the content will differ (like timestamps). Do NOT use it to silence real bugs — the underlying mismatch can still cause visual glitches and wrong content being displayed to users.
Hydration error caused by browser extension — how to fix?+
Browser extensions like Grammarly, password managers, and ad blockers inject attributes (data-lt-installed, etc.) into the DOM. This is not your bug — but you can add suppressHydrationWarning to <body> or the affected element. In development, test in a private browser window with no extensions.
How do I find which component is causing hydration error?+
Next.js 13+ shows the exact component tree in the error overlay. For older versions: add React.StrictMode warnings, check the browser console for the specific attribute or text that mismatches, and use React DevTools to inspect the hydrated tree.

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