Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

React 19 Hydration Mismatch: Error 418 and 421 Root Causes

React discards the server HTML as soon as the first client render differs. The deterministic-value fixes for #418, the attribute mismatch behind #421, and how to read the diff.

~6 min readReact
#React#Next.js#Hydration#Debugging
3D illustration of a server HTML grid slab and a client React cube grid meeting at a jagged glowing seam

Introduction & Quick Summary

Symptom. A server-rendered page flickers once after load and the console shows Minified React error #418 with the link https://react.dev/errors/418, or #421 which prints "A tree hydrated but some attributes of the server rendered HTML didn't match the client properties". The page usually still works, but event handlers attach late, layout shifts, and in Next.js the server-rendered HTML is thrown away and re-rendered on the client — visible as a flash of unstyled or different content, and bad for Core Web Vitals.

Cause. React's hydration compares the DOM produced by the server with the tree the client renders on its first pass. Any value that differs between those two renders breaks the match: Date.now(), new Date().toLocaleString() without a fixed time zone, Math.random(), browser-only reads such as window.innerWidth or localStorage, a useId mismatch between two roots, invalid HTML nesting that the browser parser silently repairs, and browser extensions that inject attributes onto <html> or <body>. Error #421 is narrower: the markup is the same but an attribute differs, and React will not patch it.

Fix. Make the first client render byte-identical to the server render. Move non-deterministic reads into useEffect or a useSyncExternalStore subscription with a server snapshot, format dates with an explicit timeZone and locale, generate ids with useId, fix nesting so the parser has nothing to repair, and use suppressHydrationWarning only on the single element whose text legitimately differs (a timestamp). Never silence a structural mismatch.

Core Mechanics, Signatures & Reproducible Setup

During hydration React walks the server HTML and the client tree in parallel; on the first disagreement inside a Suspense boundary it logs a recoverable error, discards that subtree's server HTML and renders it again on the client. React 19 reworked the messages and added a DOM diff to the warning, which is the fastest way to find the offending node: the console prints the server HTML and the client HTML side by side, with the mismatching element marked.

The codes you will meet:

tsx
// A minimal reproducer: the server has no access to window, the client does at render time 'use client'; export function Width() { const wide = typeof window !== 'undefined' && window.innerWidth > 900; return <p>{wide ? 'wide' : 'narrow'}</p>; // server: narrow, client: wide -> #418 }
tsx
// Deterministic: the first client render matches the server (both "narrow"), then updates 'use client'; import { useEffect, useState } from 'react'; export function Width() { const [wide, setWide] = useState(false); useEffect(() => { const mq = window.matchMedia('(min-width: 900px)'); setWide(mq.matches); const onChange = (e: MediaQueryListEvent) => setWide(e.matches); mq.addEventListener('change', onChange); return () => mq.removeEventListener('change', onChange); }, []); return <p>{wide ? 'wide' : 'narrow'}</p>; }

To capture mismatches in production, pass onRecoverableError to hydrateRoot; Next.js already forwards these to the console, but your own root gives you a reporting hook:

tsx
hydrateRoot(document.getElementById('root')!, <App />, { onRecoverableError(error, info) { report(error.message, info.componentStack); }, });

Key Comparison Table

CodeMessage summaryWhat differsTypical source
#418Hydration failed, tree regenerated on clientText or element structureDate, random, window reads in render
#419Server could not finish this Suspense boundaryBoundary never resolved on serverSuspense without a server-resolved promise
#421Attributes did not match, not patchedclass, style, data-*Extensions, theme scripts, ad blockers
#423Error during hydration outside a boundaryWhole root switched to clientAny thrown error during the first render
#425Text content does not matchText node onlyLocale and whitespace differences
Non-deterministic sourceBroken in renderSafe pattern
new Date()Yes, server clock and time zoneuseEffect + state, or pass ISO from server
toLocaleString()Yes, ICU data and time zoneExplicit timeZone and locale on both sides
Math.random() / crypto.randomUUID()YesuseId() for DOM ids, ids from the DB for data
window, document, localStorageYes (undefined on server)useSyncExternalStore with a server snapshot
Feature flags from cookiesYes if read differentlyRead in middleware, pass as prop
Intl.NumberFormat default localeUsually, per environmentConstruct with an explicit locale

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Server-rendered clock inside a header

Rendering "2 minutes ago" on the server guarantees a mismatch the moment network latency exceeds a minute.

tsx
// Broken <time>{new Date(post.publishedAt).toLocaleString()}</time> // Fixed: format on both sides with the same locale and zone const fmt = new Intl.DateTimeFormat('en-US', { dateStyle: 'medium', timeStyle: 'short', timeZone: 'UTC', }); <time dateTime={post.publishedAt} suppressHydrationWarning>{fmt.format(new Date(post.publishedAt))}</time>

suppressHydrationWarning belongs on that element alone and covers text and attributes one level deep. It suppresses the warning, not the mismatch: the value still differs in the DOM until the client updates it.

2. Time zone drift between build server and visitor

toLocaleString() with no options uses the runtime's zone. A container built in UTC and a visitor in Seoul get different strings, and every such page hydrates twice.

tsx
// Pin the zone once, in one module, and import it everywhere export const ZONE = 'Asia/Seoul'; export const dateFmt = new Intl.DateTimeFormat('en-GB', { timeZone: ZONE, dateStyle: 'long' });

Set TZ=UTC in the container as well, so server logs and rendered dates agree and cache keys do not depend on the host's locale.

3. useId and duplicated React roots

useId values are derived from the tree position, and two separate roots on the same page can produce the same id. If a widget is hydrated into a portal or a second container, wrap it in its own root but give inputs explicit ids from data, and never call Math.random() to dodge duplicates:

tsx
// Broken: differs between server and client const id = `field-${Math.random()}`; // Fixed const id = useId(); <label htmlFor={id}>Email</label><input id={id} name="email" />

4. Invalid HTML nesting that the parser repairs

Browsers restructure <p><div/></p>, <a><a/></a>, <table><div/>, and <button><button/>. The server sends valid-looking JSX, the browser's parser outputs a different tree, and React cannot hydrate it. The diff in the console shows the element vanishing.

tsx
// Broken <p>Total: <strong>{total}</strong>{note && <div>{note}</div>}</p> // Fixed <div>Total: <strong>{total}</strong>{note && <p>{note}</p>}</div>

5. #421 from extensions and theme scripts

Code that writes document.documentElement.className = 'dark' before hydration, or a Grammarly-style extension that adds data-gr-ext-installed to <body>, produces #421 on every page and no application bug at all. Confirm by reproducing in a clean profile, then keep the attribute tolerated:

tsx
// app/layout.tsx — the script sets the class before React runs <html lang="en" suppressHydrationWarning>

Placing the guard on <html> and <body> is the accepted pattern for theme scripts; do not add it to the component tree to hide real mismatches.

6. Suspense boundaries that resolve differently

A boundary that streams on the server but suspends again on the client produces #419, then a double render. Keep the same data promise reachable through a cache that is seeded from the server payload, as use() expects, instead of refetching in a useEffect that starts with null.

tsx
// Seed the client cache with the same data the server used <Suspense fallback={<Skeleton />}> <Comments postId={post.id} initial={post.comments} /> </Suspense>

Common Compilation/Runtime Mistakes & Version Gotchas

  • suppressHydrationWarning as a blanket fix. It hides text and attribute differences on one element; it does nothing for structural mismatches, so the tree is still regenerated and the flash remains.
  • typeof window !== 'undefined' in render. It removes the crash, not the mismatch: the server takes one branch and the client the other, which is exactly what #418 reports. Gate on a mounted flag instead.
  • React 19 changed the messages. Guides written for React 18 quote "Text content does not match server-rendered HTML"; in React 19 the same problem appears as #418 or #425, and the diff is shown inline. Search by code, not by old wording.
  • useLayoutEffect on the server. It warns during SSR and is skipped, so DOM measurements taken there differ from the browser and cascade into mismatches. Use useEffect, or useSyncExternalStore for media queries.
  • Next.js dynamic rendering. A page that is statically generated once and then rendered on the client with different data — user names from localStorage, A/B variants — will mismatch by design. Move the variant into a cookie read server-side so both renders agree.
  • React 18 hydrate() on React 19. The legacy API was removed from the client entry; only hydrateRoot exists. A vendored copy that still calls hydrate() fails at runtime, not at build.
  • Streaming and defered scripts. A third-party script that rewrites <head> before the stream finishes changes the DOM under React's feet. Load it with next/script and strategy="afterInteractive", or with defer outside the hydrated subtree.

Related tools. Diff the server HTML against the client markup with the text diff tool, decode the __next_f payload with the JSON formatter when you need the exact props the server sent, and compare two timestamp formats side by side with the timestamp converter before choosing a display format.

Try matching browser tools

All tools

Small utilities that fit React work — they run entirely in this browser tab, so nothing you paste leaves your device.

All React guides

More in React

All React guides

The guides filed next to this one in React, in library order.