Next.js Hydration: Resolving Mismatches in Modern SSR Applications

Hydration mismatches are the bane of Next.js developers. They occur when the server-rendered HTML doesn't perfectly align with the first render of the React tree on the client.
The Anatomy of a Mismatch
When you use things like window.innerWidth or localStorage inside the initial render of a React component, you're asking for trouble. The server doesn't have a window, so it renders a generic state. When the client loads, it immediately renders the "real" state. React panics because the DOM it expected isn't there.
The Solution: Two-Pass Rendering
The most robust way to handle client-only data like dark mode preferences or local storage is through a mounted state check:
const [mounted, setMounted] = useState(false);
useEffect(() => {
setMounted(true);
}, []);
if (!mounted) {
return <SkeletonLoader />;
}
return <ActualComponent />This ensures the server renders the skeleton, the client initially renders the skeleton (matching the server exactly), and then immediately updates to the correct state post-hydration.