I spun up a fresh Next.js app a few weeks back, wired up a dark mode toggle with localStorage because that’s the simplest possible approach, hit refresh, and got greeted by the single worst red stack trace in the React ecosystem: Hydration failed because the initial UI does not match what was rendered on the server. I stared at it for a solid minute assuming I’d fat-fingered something in the component. I hadn’t. This is just what happens when you store theme state somewhere the server can’t see.
The Lifecycle Anatomy of a Hydration Crash #
Here’s what I eventually worked out by actually reading through the render pipeline instead of guessing. Next.js pre-renders your HTML on a Node server, and Node doesn’t have a browser window — it has no concept of localStorage at all. So when my component checked localStorage.getItem('theme') during that server pass, it just fell through to my fallback, which was light mode. Nothing broke yet. That part’s fine.
Then the HTML lands in the browser and React takes over. It runs my component tree client-side, checks localStorage, finds "dark" sitting there from my last visit, and renders the dark theme classes. Now I’ve got two different realities: the server said class="light", the client says class="dark". React diffs them, finds a mismatch it can’t reconcile, throws its hands up, wipes the DOM tree, and dumps that hydration error straight into my console. It’s not a bug in Next.js — I want to be clear about that, because I spent a good chunk of that evening assuming it was. It’s a structural conflict: the server has zero memory of anything the browser persisted locally, full stop.
Laid out plainly, the mismatch looks like this:
| Phase | Where It Runs | Can It See localStorage | Theme It Resolves To |
|---|---|---|---|
| Server-side render | Node / edge runtime | No | Fallback (light) |
| Client-side hydration | Browser | Yes | Stored value (dark) |
| Result | React’s diff check | — | Mismatch, hydration aborts |
Why the useEffect Hack Doesn’t Actually Fix It #
My first instinct, like basically everyone’s, was to just shove the check into a useEffect:
const [isDark, setIsDark] = useState(false);
useEffect(() => {
const theme = localStorage.getItem('theme');
if (theme === 'dark') setIsDark(true);
}, []);And sure — the crash goes away. But I immediately traded it for something almost as annoying: a flash of unstyled content. useEffect only fires after the first client paint, which means my app renders in light mode every single time, for a beat, before JavaScript catches up and slaps the dark classes on. If I’ve got dark mode saved and I load the page, I get a blast of white screen first. It’s not a crash anymore, but it’s not a fix either — it’s a cosmetic patch over the same root problem, and on a slower device that flash is long enough to actually notice and be annoyed by.
Fix One: Tell React to Trust You on the Root Tag #
If you’re changing attributes on <html> or <body> based on anything client-only — theme, system preference, whatever — React is going to flag that mismatch every time unless you explicitly tell it not to. Next.js ships an escape hatch for exactly this:
// app/layout.tsx
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en" suppressHydrationWarning>
<body>{children}</body>
</html>
);
}I want to flag the obvious trap here, because I almost fell into it myself: don’t sprinkle suppressHydrationWarning across your whole component tree because it made one error go quiet. It’s meant for exactly this — a root tag whose attributes legitimately diverge between server and client on first paint. Anywhere else, it’s just hiding a real bug from yourself.
Fix Two: Kill the Flash With a Blocking Script #
Suppressing the warning stops the console from screaming, but it does nothing for the actual white flash. To get rid of that, you need a synchronous script injected into <head> that runs before the browser paints anything — before your stylesheet, before React, before any of it. It reads localStorage directly and stamps the right class onto <html> immediately.
// app/layout.tsx
import './globals.css';
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en" suppressHydrationWarning>
<head>
<script
dangerouslySetInnerHTML={{
__html: `
try {
const storedTheme = localStorage.getItem('theme');
const systemPrefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
const theme = storedTheme || (systemPrefersDark ? 'dark' : 'light');
if (theme === 'dark') {
document.documentElement.classList.add('dark');
} else {
document.documentElement.classList.remove('dark');
}
} catch (e) {}
`,
}}
/>
</head>
<body className="bg-white dark:bg-zinc-950 text-zinc-900 dark:text-zinc-50">
{children}
</body>
</html>
);
}The try/catch around it isn’t decoration — some browsers block localStorage entirely in private/incognito modes or under strict cookie settings, and without that guard, a blocked read throws and kills the entire inline script before it reaches your class logic. I learned that one from a bug report, not from thinking ahead.
Fix Three: A Toggle That Doesn’t Fight Its Own Hydration #
Once the root <html> tag is already correctly themed before React even mounts, your toggle component still has to read that state back without re-triggering the same mismatch. The move is a mount guard — don’t render the real interactive button until you know you’re on the client:
'use client';
import { useState, useEffect } from 'react';
export function ThemeToggle() {
const [mounted, setMounted] = useState(false);
const [isDark, setIsDark] = useState(false);
useEffect(() => {
setMounted(true);
setIsDark(document.documentElement.classList.contains('dark'));
}, []);
const toggleTheme = () => {
const newTheme = !isDark;
setIsDark(newTheme);
if (newTheme) {
document.documentElement.classList.add('dark');
localStorage.setItem('theme', 'dark');
} else {
document.documentElement.classList.remove('dark');
localStorage.setItem('theme', 'light');
}
};
if (!mounted) {
return <div className="w-8 h-8" />;
}
return (
<button
onClick={toggleTheme}
className="p-2 rounded-lg border border-zinc-300 dark:border-zinc-700 transition-colors"
aria-label="Toggle Theme"
>
{isDark ? 'Light mode' : 'Dark mode'}
</button>
);
}That placeholder div during the unmounted state matters more than it looks — without it, you get a layout shift the instant the real button pops in, which is its own small annoyance stacked on top of everything else you just fixed.
Three pieces, and they’re not interchangeable — skip the blocking script and you’re back to FOUC even with suppressHydrationWarning in place; skip the mount guard and your toggle itself can desync on fast refreshes. Put all three in, and the app boots with the right theme already painted, no flash, no console error, no civil war between what the server thought and what the browser knew. The server was never going to know what was in localStorage. The whole fix is just accepting that and routing around it instead of pretending it isn’t true.