DEV3 Technologies home

DEV3 Developer Forum

How do I fix 'Hydration failed because the initial UI does not match' in Next.js?

Next.js helpSolved0 views
dev3 ·

After upgrading to React 19 and Next.js 15 I get:

Error: Hydration failed because the server rendered HTML didn't match the client.

It only happens on some pages. How do I find the cause and fix it?

#nextjs#react#hydration

0

1 reply

dev3 · Accepted answer

Hydration compares the HTML from the server with what React renders first in the browser. Any difference triggers this error.

Common causes

  1. Non-deterministic values in render: Date.now(), new Date().toLocaleString(), Math.random(), crypto.randomUUID().
  2. Browser-only checks: typeof window !== "undefined" ? a : b inside render.
  3. Invalid HTML nesting: <div> inside <p>, <a> inside <a>, <tr> directly in <table> without <tbody> in some cases.
  4. Browser extensions that inject attributes (dark mode, translation, password managers).
  5. localStorage or cookies read during the first render.

Fixes

Render the same thing first, then update after mount:

"use client";
import { useEffect, useState } from "react";

export function LocalTime({ iso }: { iso: string }) {
  const [text, setText] = useState(iso);
  useEffect(() => {
    setText(new Date(iso).toLocaleString());
  }, [iso]);
  return <time dateTime={iso}>{text}</time>;
}

For unavoidable single-element mismatches (a timestamp) you can add suppressHydrationWarning to that element only. It works one level deep and does not fix real structure mismatches.

For client-only widgets use next/dynamic with ssr: false inside a client component.

Debugging

React 19 prints a diff of the mismatching tree in the console, so read it rather than just the headline. Test in a private window with extensions disabled. Also check the HTML nesting by viewing page source.

Pitfall: setting theme from localStorage in render causes this for dark mode. Use a small inline script plus CSS variables, or next-themes, which handles it.

0

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.