Next.jsMedium
What are hydration errors and how do you fix them?
A hydration error happens when the HTML React renders in the browser during hydration differs from the HTML the server sent. React then discards and re-renders that part on the client, which is slower and can cause flicker. Fix it by making the first client render identical to the server render.
Common causes
- Time and randomness:
new Date(),Date.now(),Math.random()rendered directly. - Browser-only checks during render:
typeof window !== "undefined" ? A : B,localStorage,navigator. - Locale and time zone differences:
toLocaleString()with different server and user settings. - Invalid HTML nesting:
<p>inside<p>,<div>inside<p>,<a>inside<a>, missing<tbody>. - Browser extensions that modify the DOM (Grammarly, translators, password managers).
- CSS-in-JS misconfiguration, or data that changes between server and client fetch.
Fixes
- Defer client-only values to
useEffect, rendering a stable placeholder first. - Use
useSyncExternalStorewith a server snapshot for browser values. - Skip SSR for a component with
next/dynamicandssr: false(from a Client Component). - Pass values from the server: read cookies or headers on the server so both renders agree.
- Format with explicit locale and timeZone.
suppressHydrationWarningon a single element for unavoidable cases like timestamps. It only works one level deep; do not spread it around.- Fix HTML nesting.
Debugging
The Next.js error overlay shows the component stack and, since 16.2, a diff of server versus client output. Test in an incognito window to rule out extensions. For theme flashes, set a class from a cookie on the server, or see the "Preventing flash before hydration" guide.
Code example
tsx
1// app/greeting.tsx2"use client";34import { useEffect, useState } from "react";56// Bad: differs between server and browser7// export function Greeting() {8// const hour = new Date().getHours();9// return <p>{typeof window === "undefined" ? "Hello" : hour < 12 ? "Good morning" : "Good evening"}</p>;10// }1112// Good: identical first render, client-specific value applied after hydration13export function Greeting() {14 const [text, setText] = useState("Hello");1516 useEffect(() => {17 setText(new Date().getHours() < 12 ? "Good morning" : "Good evening");18 }, []);1920 return <p>{text}</p>;21}2223// Invalid nesting also causes hydration errors:24// <p>Intro <div>block</div></p> -> use <div> or <span> instead
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.