Repository navigation
Description
Bug: hydration cursor is not rewound when a host fiber is replayed, so hydration fails on an identical tree
React version
19.2.8 (react and react-dom from npm, no framework). Also present in the
React 19.2 canary bundled with Next.js 15.5.9, which is where we hit it first.
Steps To Reproduce
git clone https://github.com/dreamerhyde/react-hydration-replay-repro && cd react-hydration-replay-repronpm install && npm run buildnpm run probe-- loads the page 20 times per cell with Playwright and prints
the table below. Ornpm run serveand open http://127.0.0.1:8117/ with
the console open.
The tree is:
// pendingChunk(): a thenable in React's "status / value" protocol, pending when
// React first renders it, fulfilled one microtask later.
const lazyChild = React.lazy(() =>
pendingChunk({ default: <section id="child">lazy child</section> }),
);
function App() {
return (
<div id="outer">
<p id="before">before</p>
<div id="target">{lazyChild}</div> {/* lazy NODE, not <Lazy /> */}
<p id="after">after</p>
</div>
);
}Rendered with renderToPipeableStream on the server (so the served HTML already
contains <section id="child">), hydrated with
startTransition(() => hydrateRoot(container, <App />)) on the client, which is
what Next.js does and what puts the hydration render on a time-sliced lane.
Link to code example
The current behavior
Hydration fails on every load even though the server and client trees are
identical. React discards the server-rendered DOM and re-renders the whole root
on the client.
react-dom 19.2.8, 20 page loads per cell
| page | react-dom | loads with a hydration error | loads that discarded the server DOM |
| ------------------------------- | ---------- | ---------------------------- | ----------------------------------- |
| production | unpatched | 20/20 | 20/20 |
| development | unpatched | 20/20 | 20/20 |
| production | patched | 0/20 | 0/20 |
| development | patched | 0/20 | 0/20 |
| production, no startTransition | unpatched | 0/20 | 0/20 |
| production, chunk resolves late | unpatched | 0/20 | 0/20 |
("patched" = with the fix below applied to the installed react-dom; the last two
rows are controls, see Mechanism.)
Production build, reported through onRecoverableError:
Minified React error #418; visit https://react.dev/errors/418?args[]=HTML&args[]= for the full message
Development build, same load:
Hydration failed because the server rendered HTML didn't match the client. As a result this tree will be regenerated on the client.
...
<App>
<div id="outer">
<p>
+ <div id="target">
- <section id="child">
...
React is trying to hydrate <div id="target"> against the node inside
<div id="target">.
The expected behavior
Server and client render the same tree, so hydration should succeed and the
server-rendered DOM should be reused.
Mechanism
Line numbers from [email protected], cjs/react-dom-client.production.js.
beginWorkcase 5 claims the DOM node for<div id="target">(upstream
tryToClaimNextHydratableInstance, inlined in the published build): it sets
hydrationParentFiber = workInProgressand movesnextHydratableInstance
into that div, to<section id="child">.- Reconciling that div's children resolves the lazy node,
resolveLazy(3254)
throwsSuspenseException-- whileworkInProgressis still the div. handleThrow(11053) records reason 3 (SuspendedOnImmediate).renderRootConcurrent(11184) turns reason 3 into reason 7 and yields. The
chunk is fulfilled during that yield.- Next slice: reason 7 sees
isThenableResolvedtrue (3197) and calls
replaySuspendedUnitOfWork(11309) on the div. - That function's default branch does
unwindInterruptedWork(8533, pops host
context only) andresetWorkInProgress(2489). Neither restores
hydrationParentFiber/nextHydratableInstance--popHydrationState
(2835) only runs fromcompleteWork. beginWorkruns again for the div with the cursor still at
<section id="child">,canHydrateInstance(14134) fails,
throwOnHydrationMismatch(2735) queues #114 - stop requiring docblock for JSX transformer #418, and with no<Suspense>
handler above itthrowException(5960) re-renders the whole root
(mountHostRootWithoutHydrating, 6805).
Three conditions have to line up, and all three are ordinary in a Flight / RSC
app, which is why this shows up as an intermittent hydration error in
production and is hard to attribute:
- The lazy is in the children position (a lazy node, what Flight's
createLazyChunkWrapperproduces for a$Lrow), so it suspends while the
unit of work is the parent host fiber. As<Lazy />it would get its own
fiber (tag 16) and the replay would be harmless. - The thenable carries
status(Flight chunks do; so does anything written
foruse(thenable)). The replay path is only taken when
isThenableResolved(thenable)is true, and a barePromisenever has a
status, so it unwinds to the root instead and hydrates cleanly. - It is fulfilled inside the yield, after React throws and before its next
slice. Fulfilling it 50ms later (?resolve=late) unwinds and hydrates
cleanly; asetTimeout(fn, 0)still lands inside the window.
Also, replaySuspendedUnitOfWork only exists in renderRootConcurrent --
renderRootSync unwinds for the same reason -- so the hydration render has to
be time-sliced. ?transition=0 (hydrate without startTransition) is clean.
In a large tree the mismatch can surface several levels below the replayed
fiber (that is how we first saw it): production builds do not compare attributes, so a
mis-positioned cursor is accepted for as long as the tags line up, and the
error is finally attributed to some unrelated component.
Proposed fix
Restore the hydration cursor before replaying a host fiber that already claimed
an instance:
function replaySuspendedUnitOfWork(unitOfWork) {
if (
isHydrating &&
hydrationParentFiber === unitOfWork &&
null !== unitOfWork.stateNode &&
(5 === unitOfWork.tag || 26 === unitOfWork.tag)
) {
nextHydratableInstance = unitOfWork.stateNode;
popToNextHostParent(unitOfWork);
}
// ... existing body
}hydrationParentFiber === unitOfWork is true only for a host fiber that has
already claimed its instance and pushed the cursor inside itself, so
replayFunctionComponent (tags 0/11) and host fibers that suspended before
claiming anything are untouched. Tag 27 (HostSingleton) is deliberately
excluded: its stateNode comes from resolveSingletonInstance, not from the
cursor, and its pre-claim cursor lives in
previousHydratableOnEnteringScopedSingleton, so it needs a different rewind.
With counters added to replaySuspendedUnitOfWork and
throwOnHydrationMismatch, the fix does not remove the replay -- every load
still replays the same {tag: 5, hydrationParentFiber === unitOfWork} fiber; it
just stops the mismatch:
| react-dom | replays per load | mismatches per load | recoverable errors |
|---|---|---|---|
| unpatched | 1 | 1 | 1 |
| patched | 1 | 0 | 0 |
I am happy to open a PR with this change plus a hydration test if the approach
looks right.
Activity
dreamerhyde commentedon Sep 11, 2026
Cross-reference: this looks like the same symptom as #26181 ("Bug: lazy + hydrateRoot + sibling = mismatch", React 18.2), which was closed as stale in 2024-04 with the bot asking for a fresh issue with a reproduction. The repro linked above (https://github.com/dreamerhyde/react-hydration-replay-repro) is deterministic (20/20 failing runs → 0/20 with the 3-line change described in the issue body), so this can serve as the reproduction that issue was missing.
eps1lon commentedon Sep 11, 2026
Can you transform this into a failing React test matching our e2e-like testing style? The test would assert on the hydration error with
assertConsoleErrorDevto characterize the bug.dreamerhyde commentedon Sep 12, 2026
Done, but with a finding that changes the shape of the answer: while writing the test I found that
mainalready contains this fix, and it shipped three days ago.replayBeginWork'sHostComponentcase now callspopHydrationStateOnInterruptedWork(unitOfWork), which restoresnextHydratableInstanceto the fiber's ownstateNodeand pops to the next host parent -- the same thing the three lines in the issue body do.v19.2.8does not containc18662405, and the published[email protected]bundle has nopopHydrationStateOnInterruptedWork. My repro was pinned to 19.2.8 and Next.js 15.5.9 bundles a 19.2 canary, which is why we still hit it.So this is a 19.2.x-only bug now. The remaining question from my side is whether a 19.2.x patch release is planned; otherwise "upgrade to 19.3.0" closes this.
A test in the
assertConsoleErrorDevform cannot pass onmainbecause the error is gone, so here are both forms, in the Fizz +hydrateRootstyle ofReactDOMFizzShellHydration-test.js. Both were run againstmain@019019beand againstmainwith the one restore line removed.Form A: regression test (passes on
main, fails without #35494)packages/react-dom/src/__tests__/ReactDOMFizzHydrationReplay-test.jsRemoving the single line
popHydrationStateOnInterruptedWork(unitOfWork);fromreplayBeginWorkturns it red with exactly the diff from the issue body:The control
it(same tree, nostartTransition) stays green in both directions, which pins the failure to the time-sliced replay path.Form B: the
assertConsoleErrorDevformSame file, with the last assertions of the first
itreplaced by the block below (andbeforeEachpointingglobal.window/global.document/global.navigator/global.Node/global.addEventListenerat the jsdom instance the wayReactDOMFloat-test.jsdoes, otherwise the recoverable error surfaces as an uncaught jsdom error instead of aconsole.error):This one passes with the restore line removed (2 passed) and fails on unmodified
main(beforeis no longer logged a second time, and there is no console error), i.e. it characterizes the bug against the pre-#35494 code.How the timing is pinned
The bug needs the chunk to become fulfilled inside the yield: after React records
SuspendedOnImmediateand breaks out of the work loop, before its next slice. The test does not rely on a microtask for that. TheReact.lazyctor logsread chunkat the moment it suspends,await waitFor(['before', 'read chunk'])stopsSchedulerMockat that yield, then the test flipschunk.statusto'fulfilled'by hand and synchronously calls thethencallback thatlazyInitializerregistered. The next slice seesisThenableResolved(thenable)and takesreplaySuspendedUnitOfWork. Two things confirm it is the replay path rather than an unwind:beforeis not logged a second time (an unwind to the root re-renders the whole tree), and instrumentingreplaySuspendedUnitOfWorkto printunitOfWork.tagyields exactly onetag: 5.One coverage note:
replayBeginWorkrestores the cursor only forHostComponent;HostSingletonfalls through to the default branch. I probed that shape (hydrateRoot(document, ...)with the lazy node directly under<body>) and it hydrates correctly onmain, and not vacuously: the same instrumentation shows it goes throughreplaySuspendedUnitOfWorkwithtag: 27.<body>'sstateNodecomes fromresolveSingletonInstancerather than from the cursor, so re-runningbeginWorkdoes not depend on the cursor there.Happy to open a PR adding Form A as a regression test if that is useful.
eps1lon commentedon Sep 14, 2026
Thank you for digging. Glad to hear it's already fixed. We're not backporting bug fixes to prior SemVer minor releases.
docs: correct the hydration write-up — the warning survives in produc…
Evita o erro 418 do React quando o chunk do error.tsx atrasa (#91)
Page audit: the intermittent #418 is React's replay bug; the fix is t…
Page audit: backport React's hydration replay fix (react/react#37584)
React replay backport: inject React 19.3's own fix, and leave a React…
Hold the replay backport test to Next 16's React, which ships the fix
Hold the replay backport test to Next 16's React, which ships the fix
fix(website): work around React hydration replay bug on docs pages in…
fix(website): work around React hydration replay bug on docs pages in…
M15: upstream React/Next hydration #418 evidence package (docs only)
Upgrade Next.js to 16.2.12
chore(deps): 升級 Next.js 16.4.5 修復 root hydration #418