How to Fix a Next.js Hydration Error Caused by localStorage

At a glance
Use a browser profile with no saved value, load the page directly and note the first rendered state. Then save a different preference and reload the same URL. Test navigation to the page as well as a hard refresh; client navigation can hide a server-render mismatch.
A hydration error can be confusing: your page may look correct after it loads, yet Next.js reports that the HTML rendered on the server does not match what React expects in the browser. One common cause is reading localStorage while rendering a component.
This guide explains why that mismatch happens, how to reproduce it, and how to choose a fix that matches your interface. The examples use the App Router and React hooks. Test them in your own project before shipping.
Test a stored preference on the first page load
Use a browser profile with no saved value, load the page directly and note the first rendered state. Then save a different preference and reload the same URL. Test navigation to the page as well as a hard refresh; client navigation can hide a server-render mismatch.
The server cannot read localStorage. Keep the server render and the initial client render consistent, then read browser storage after mounting if that is the chosen design. Catch storage failures, because browser policy can make access throw.
If the preference must affect the server response, use a suitable server-readable mechanism such as a cookie and think through caching and privacy. Avoid suppressHydrationWarning as a blanket fix for an unexplained mismatch. Also check invalid HTML, timestamps and browser extensions: not every hydration error is caused by storage.
Reference: React hydrateRoot caveats.
What does a hydration error mean?
With server rendering, Next.js can generate HTML before browser JavaScript runs. React then hydrates that HTML, attaching behavior and reconciling it with the component tree rendered in the browser. If the initial browser render differs from the server-rendered output, React may report a hydration mismatch.
Typical messages mention that the server-rendered HTML did not match the client, or that hydration failed because the initial UI differed. The exact wording can vary by React and Next.js version.
Why localStorage causes the mismatch
localStorage is a browser API. It is not available in the server rendering environment. Imagine a theme component that reads a saved preference during render:
"use client";
export default function ThemeLabel() {
const theme = localStorage.getItem("theme") ?? "light";
return <p>Current theme: {theme}</p>;
}
This example is unsafe because the component reads a browser-only API during render. It can also fail when the code executes where localStorage does not exist. Even if you add a guard, rendering one value on the server and another on the first browser render can still create a mismatch.
Fix 1: Read localStorage inside useEffect
For many preference displays, the straightforward fix is to render a stable initial value and read the saved value after the component mounts:
"use client";
import { useEffect, useState } from "react";
export default function ThemeLabel() {
const [theme, setTheme] = useState("light");
useEffect(() => {
const savedTheme = window.localStorage.getItem("theme");
if (savedTheme) {
setTheme(savedTheme);
}
}, []);
return <p>Current theme: {theme}</p>;
}
The server render and the initial browser render both start with "light". After mounting, the effect reads the browser storage and updates state if a saved preference exists. This avoids using localStorage to calculate the initial rendered output.
Trade-off: the user may briefly see the default value before the saved value appears. For a theme that changes the entire page, consider whether that flash is acceptable and whether a cookie-based approach would better fit your requirements.
Fix 2: Use a cookie when the server needs the preference
If a preference must affect the first HTML response—for example, a theme that changes the whole page—store it in a cookie that the browser sends with the request. Next.js can read request cookies in server components using the cookies API. Cookie access affects rendering behavior, so review the current Next.js documentation before choosing this architecture.
Cookies and localStorage are not interchangeable in every situation. Cookies are sent with matching requests and need appropriate options; localStorage stays in the browser and is not automatically sent to your server. Never put secrets or authentication tokens in client-readable storage without understanding the security implications.
Official reference: https://nextjs.org/docs/app/api-reference/functions/cookies
Fix 3: Render a client-only widget when appropriate
Some widgets depend on browser-only APIs, such as a visual editor that reads browser storage or a library that accesses window during initialization. In those cases, a client-only loading strategy may be appropriate. Next.js supports lazy loading and disabling server-side rendering for supported client component imports, but use this selectively: removing server rendering can affect initial content, accessibility, and perceived loading.
Do not disable server rendering for an entire page just to hide a single mismatch. Isolate the browser-dependent component instead.
Reference: https://nextjs.org/docs/app/guides/lazy-loading
Avoid this common “fix”
A pattern like this may appear to solve the problem:
const value =
typeof window !== "undefined"
? localStorage.getItem("theme")
: "light";
It protects against accessing window on the server, but it does not guarantee that the server and the browser's first render return the same value. If storage contains "dark", the server can render "light" while the browser initially renders "dark". The environment check alone does not solve the mismatch.
A practical debugging checklist
- Find any render-time access to
window,document,localStorage, orsessionStorage. - Check whether the server and first browser render produce identical markup.
- Move browser-only reads into
useEffectwhen a post-mount update is acceptable. - Use cookies when the server needs the preference before generating HTML.
- Isolate browser-dependent libraries instead of disabling SSR across a whole page.
- Check for other mismatch causes, including invalid HTML nesting, changing timestamps, random values, and extensions that alter the DOM.
- Reproduce the issue in a production build as well as development mode.
Frequently asked questions
Does adding "use client" fix localStorage hydration errors?
Not automatically. A Client Component can still be pre-rendered for the initial page load. "use client" defines a client component boundary; it does not mean every expression is only evaluated after the browser mounts.
Should I use useEffect for every localStorage read?
Use it when the value can be read after mounting without harming the experience. If the value must determine the initial server HTML, consider a server-readable preference such as a cookie instead.
Is suppressHydrationWarning the right fix?
Usually not for this problem. It suppresses a warning in limited cases; it does not make inconsistent rendering logic correct. Fix the source of the mismatch where possible.
Research and references
- Next.js: Server and Client Components — https://nextjs.org/docs/app/getting-started/server-and-client-components
- Next.js:
cookiesAPI — https://nextjs.org/docs/app/api-reference/functions/cookies - Next.js: Lazy Loading — https://nextjs.org/docs/app/guides/lazy-loading
- React:
useEffect— https://react.dev/reference/react/useEffect - React: Hydration error guidance — https://react.dev/link/hydration-mismatch
If hydration warnings started after an upgrade, review the Next.js 16 migration guide alongside the local storage checks.
Try our QR Code Generator
Create clean, scannable QR codes for testing websites, URLs, and client handoffs.

Ukasha Altaf
Software Developer & Digital Tools Creator
Founder of Ukasha Mart. Building free, accessible browser-based utilities and writing in-depth tutorials on modern technology, freelancing, and practical online work.
Explore Further