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

  1. Defer client-only values to useEffect, rendering a stable placeholder first.
  2. Use useSyncExternalStore with a server snapshot for browser values.
  3. Skip SSR for a component with next/dynamic and ssr: false (from a Client Component).
  4. Pass values from the server: read cookies or headers on the server so both renders agree.
  5. Format with explicit locale and timeZone.
  6. suppressHydrationWarning on a single element for unavoidable cases like timestamps. It only works one level deep; do not spread it around.
  7. 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.tsx
2"use client";
3
4import { useEffect, useState } from "react";
5
6// Bad: differs between server and browser
7// export function Greeting() {
8// const hour = new Date().getHours();
9// return <p>{typeof window === "undefined" ? "Hello" : hour < 12 ? "Good morning" : "Good evening"}</p>;
10// }
11
12// Good: identical first render, client-specific value applied after hydration
13export function Greeting() {
14 const [text, setText] = useState("Hello");
15
16 useEffect(() => {
17 setText(new Date().getHours() < 12 ? "Good morning" : "Good evening");
18 }, []);
19
20 return <p>{text}</p>;
21}
22
23// 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.

Open in study app