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.

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:
// 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
}// 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:
hydrateRoot(document.getElementById('root')!, <App />, {
onRecoverableError(error, info) {
report(error.message, info.componentStack);
},
});Key Comparison Table
| Code | Message summary | What differs | Typical source |
|---|---|---|---|
| #418 | Hydration failed, tree regenerated on client | Text or element structure | Date, random, window reads in render |
| #419 | Server could not finish this Suspense boundary | Boundary never resolved on server | Suspense without a server-resolved promise |
| #421 | Attributes did not match, not patched | class, style, data-* | Extensions, theme scripts, ad blockers |
| #423 | Error during hydration outside a boundary | Whole root switched to client | Any thrown error during the first render |
| #425 | Text content does not match | Text node only | Locale and whitespace differences |
| Non-deterministic source | Broken in render | Safe pattern |
|---|---|---|
new Date() | Yes, server clock and time zone | useEffect + state, or pass ISO from server |
toLocaleString() | Yes, ICU data and time zone | Explicit timeZone and locale on both sides |
Math.random() / crypto.randomUUID() | Yes | useId() for DOM ids, ids from the DB for data |
window, document, localStorage | Yes (undefined on server) | useSyncExternalStore with a server snapshot |
| Feature flags from cookies | Yes if read differently | Read in middleware, pass as prop |
Intl.NumberFormat default locale | Usually, per environment | Construct 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.
// 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.
// 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:
// 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.
// 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:
// 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.
// 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
suppressHydrationWarningas 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.
useLayoutEffecton the server. It warns during SSR and is skipped, so DOM measurements taken there differ from the browser and cascade into mismatches. UseuseEffect, oruseSyncExternalStorefor 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; onlyhydrateRootexists. A vendored copy that still callshydrate()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 withnext/scriptandstrategy="afterInteractive", or withdeferoutside 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 toolsSmall utilities that fit React work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related React guides
All React guidesReact Maximum Update Depth Exceeded: Finding the Update Loop
Fifty nested updates and React gives up. The loop is always a new identity: an inline object in a dependency array, a setState in render, or a selector that returns a fresh array.
React Profiler API: Measuring Render Timings and Identifying Wasted Re-Renders
actualDuration versus baseDuration, phase names that tell you who triggered a commit, and how to ship the numbers without flooding a backend.
React with TypeScript: Generic Components, PropsWithChildren, and Event Types
Generic props that infer from data, PropsWithChildren instead of React.FC, and element-scoped event types that keep currentTarget typed.
React useTransition and useDeferredValue: Non-Blocking Concurrent UI Updates
Transitions let React throw away background work when typing arrives. Which hook defers what, and why a controlled input must never be transitioned.
More in React
All React guidesThe guides filed next to this one in React, in library order.