Skip to content

Bug: hydration cursor is not rewound when a host fiber is replayed, so hydration fails on an identical tree #37584

Closed

Description

@dreamerhyde

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

  1. git clone https://github.com/dreamerhyde/react-hydration-replay-repro && cd react-hydration-replay-repro
  2. npm install && npm run build
  3. npm run probe -- loads the page 20 times per cell with Playwright and prints
    the table below. Or npm run serve and 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

https://github.com/dreamerhyde/react-hydration-replay-repro

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.

  1. beginWork case 5 claims the DOM node for <div id="target"> (upstream
    tryToClaimNextHydratableInstance, inlined in the published build): it sets
    hydrationParentFiber = workInProgress and moves nextHydratableInstance
    into that div, to <section id="child">.
  2. Reconciling that div's children resolves the lazy node, resolveLazy (3254)
    throws SuspenseException -- while workInProgress is still the div.
  3. handleThrow (11053) records reason 3 (SuspendedOnImmediate).
  4. renderRootConcurrent (11184) turns reason 3 into reason 7 and yields. The
    chunk is fulfilled during that yield.
  5. Next slice: reason 7 sees isThenableResolved true (3197) and calls
    replaySuspendedUnitOfWork (11309) on the div.
  6. That function's default branch does unwindInterruptedWork (8533, pops host
    context only) and resetWorkInProgress (2489). Neither restores
    hydrationParentFiber / nextHydratableInstance -- popHydrationState
    (2835) only runs from completeWork.
  7. beginWork runs 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 it throwException (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
    createLazyChunkWrapper produces for a $L row), 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
    for use(thenable)). The replay path is only taken when
    isThenableResolved(thenable) is true, and a bare Promise never 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; a setTimeout(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

  1. dreamerhyde commented on Sep 11, 2026

    @dreamerhyde
    Author

    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.

  2. eps1lon commented on Sep 11, 2026

    @eps1lon
    Collaborator

    Can you transform this into a failing React test matching our e2e-like testing style? The test would assert on the hydration error with assertConsoleErrorDev to characterize the bug.

  3. added
    Status: Unconfirmed
    on Sep 11, 2026
  4. dreamerhyde commented on Sep 12, 2026

    @dreamerhyde
    Author

    Done, but with a finding that changes the shape of the answer: while writing the test I found that main already contains this fix, and it shipped three days ago.

    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 assertConsoleErrorDev form cannot pass on main because the error is gone, so here are both forms, in the Fizz + hydrateRoot style of ReactDOMFizzShellHydration-test.js. Both were run against main @ 019019be and against main with the one restore line removed.

    Form A: regression test (passes on main, fails without #35494)

    packages/react-dom/src/__tests__/ReactDOMFizzHydrationReplay-test.js

    /**
     * Copyright (c) Meta Platforms, Inc. and affiliates.
     *
     * This source code is licensed under the MIT license found in the
     * LICENSE file in the root directory of this source tree.
     *
     * @emails react-core
     * @jest-environment ./scripts/jest/ReactDOMServerIntegrationEnvironment
     */
    
    'use strict';
    
    let JSDOM;
    let React;
    let startTransition;
    let ReactDOMClient;
    let ReactDOMFizzServer;
    let Scheduler;
    let Stream;
    let document;
    let writable;
    let container;
    let buffer = '';
    let hasErrored = false;
    let fatalError = undefined;
    let assertLog;
    let waitFor;
    let waitForAll;
    
    describe('ReactDOMFizzHydrationReplay', () => {
      beforeEach(() => {
        jest.resetModules();
        JSDOM = require('jsdom').JSDOM;
        React = require('react');
        ReactDOMClient = require('react-dom/client');
        ReactDOMFizzServer = require('react-dom/server');
        Scheduler = require('scheduler');
        Stream = require('stream');
    
        const InternalTestUtils = require('internal-test-utils');
        assertLog = InternalTestUtils.assertLog;
        waitFor = InternalTestUtils.waitFor;
        waitForAll = InternalTestUtils.waitForAll;
    
        startTransition = React.startTransition;
    
        // Test Environment
        const jsdom = new JSDOM(
          '<!DOCTYPE html><html><head></head><body><div id="container">',
          {
            runScripts: 'dangerously',
          },
        );
        document = jsdom.window.document;
        container = document.getElementById('container');
    
        buffer = '';
        hasErrored = false;
    
        writable = new Stream.PassThrough();
        writable.setEncoding('utf8');
        writable.on('data', chunk => {
          buffer += chunk;
        });
        writable.on('error', error => {
          hasErrored = true;
          fatalError = error;
        });
      });
    
      afterEach(() => {
        jest.restoreAllMocks();
      });
    
      async function serverAct(callback) {
        await callback();
        // Await one turn around the event loop.
        // This assumes that we'll flush everything we have so far.
        await new Promise(resolve => {
          setImmediate(resolve);
        });
        if (hasErrored) {
          throw fatalError;
        }
        // JSDOM doesn't support stream HTML parser so we need to give it a proper fragment.
        // We also want to execute any scripts that are embedded.
        // We assume that we have now received a proper fragment of HTML.
        const bufferedContent = buffer;
        buffer = '';
        const fakeBody = document.createElement('body');
        fakeBody.innerHTML = bufferedContent;
        while (fakeBody.firstChild) {
          const node = fakeBody.firstChild;
          if (node.nodeName === 'SCRIPT') {
            const script = document.createElement('script');
            script.textContent = node.textContent;
            fakeBody.removeChild(node);
            container.appendChild(script);
          } else {
            container.appendChild(node);
          }
        }
      }
    
      // A thenable in React's "status"/"value" protocol: the shape a Flight chunk
      // has, and the shape `use(thenable)` accepts. The status field is what
      // `isThenableResolved` reads, and that is what decides between replaying the
      // suspended unit of work and unwinding it, so a bare Promise would take a
      // different path.
      function createPendingChunk() {
        const chunk = {
          status: 'pending',
          value: null,
          reason: null,
          listeners: [],
          then(resolve) {
            if (chunk.status === 'fulfilled') {
              resolve(chunk.value);
            } else {
              chunk.listeners.push(resolve);
            }
          },
        };
        return chunk;
      }
    
      // Fulfilling is driven by the test instead of by a microtask so that it
      // lands in a known place relative to React's work loop.
      function fulfillChunk(chunk, value) {
        chunk.status = 'fulfilled';
        chunk.value = value;
        const listeners = chunk.listeners;
        chunk.listeners = [];
        listeners.forEach(listener => listener(value));
      }
    
      function createLazyNode(chunk) {
        return React.lazy(() => {
          Scheduler.log('read chunk');
          return chunk;
        });
      }
    
      function lazyChildModule() {
        return {default: <section id="child">lazy child</section>};
      }
    
      function Before() {
        Scheduler.log('before');
        return <p id="before">before</p>;
      }
    
      function After() {
        Scheduler.log('after');
        return <p id="after">after</p>;
      }
    
      function App({lazyNode}) {
        return (
          <div id="outer">
            <Before />
            {/* A lazy *node* in the children position, which is what Flight emits
                for a `$L` row. It suspends while the unit of work is still the
                parent host fiber, rather than getting a fiber of its own. */}
            <div id="target">{lazyNode}</div>
            <After />
          </div>
        );
      }
    
      async function serverRender() {
        const chunk = createPendingChunk();
        fulfillChunk(chunk, lazyChildModule());
        await serverAct(async () => {
          const {pipe} = ReactDOMFizzServer.renderToPipeableStream(
            <App lazyNode={createLazyNode(chunk)} />,
          );
          pipe(writable);
        });
      }
    
      it('hydrates a host fiber that is replayed after suspending on a lazy child', async () => {
        await serverRender();
        assertLog(['before', 'read chunk', 'after']);
        expect(container.querySelector('#target').innerHTML).toBe(
          '<section id="child">lazy child</section>',
        );
    
        const serverTarget = container.querySelector('#target');
        const serverChild = container.querySelector('#child');
    
        // The client starts with the chunk still pending.
        const chunk = createPendingChunk();
    
        // Hydrating inside startTransition is what Next.js does, and it is what
        // puts the hydration render on a time-sliced lane. `replaySuspendedUnitOfWork`
        // only exists in `renderRootConcurrent`.
        startTransition(() => {
          ReactDOMClient.hydrateRoot(
            container,
            <App lazyNode={createLazyNode(chunk)} />,
          );
        });
    
        // Render until the lazy node suspends. At this point `<div id="target">`
        // has already claimed its DOM node and the hydration cursor has moved
        // inside it, to `<section id="child">`. React has yielded to the main
        // thread with SuspendedAndReadyToContinue.
        await waitFor(['before', 'read chunk']);
    
        // Fulfill inside that yield, before React's next slice. This is what makes
        // React take the replay path instead of unwinding: the next slice sees
        // `isThenableResolved` and calls `replaySuspendedUnitOfWork` on the div.
        fulfillChunk(chunk, lazyChildModule());
    
        // Only the suspended host fiber is replayed. `before` is not logged a
        // second time, which is how this differs from unwinding to the root.
        await waitForAll(['after']);
    
        expect(container.querySelector('#target')).toBe(serverTarget);
        expect(container.querySelector('#child')).toBe(serverChild);
      });
    
      // Control: the same tree hydrated without startTransition. `renderRootSync`
      // unwinds instead of replaying, so this path is unaffected either way.
      it('hydrates the same tree when the hydration render is not time-sliced', async () => {
        await serverRender();
        assertLog(['before', 'read chunk', 'after']);
    
        const serverTarget = container.querySelector('#target');
        const serverChild = container.querySelector('#child');
    
        const chunk = createPendingChunk();
        ReactDOMClient.hydrateRoot(
          container,
          <App lazyNode={createLazyNode(chunk)} />,
        );
    
        await waitFor(['before', 'read chunk']);
        fulfillChunk(chunk, lazyChildModule());
        await waitForAll(['before', 'after']);
    
        expect(container.querySelector('#target')).toBe(serverTarget);
        expect(container.querySelector('#child')).toBe(serverChild);
      });
    });
    $ yarn test packages/react-dom/src/__tests__/ReactDOMFizzHydrationReplay-test.js
    Tests:       2 passed, 2 total
    

    Removing the single line popHydrationStateOnInterruptedWork(unitOfWork); from replayBeginWork turns it red with exactly the diff from the issue body:

      ● ReactDOMFizzHydrationReplay › hydrates a host fiber that is replayed after suspending on a lazy child
    
        Hydration failed because the server rendered HTML didn't match the client. [...]
    
          <App lazyNode={{...}}>
            <div id="outer">
              <Before>
        +     <div id="target">
        -     <section id="child">
              ...
    
          at throwOnHydrationMismatch (packages/react-reconciler/src/ReactFiberHydrationContext.js:399:15)
          at tryToClaimNextHydratableInstance (packages/react-reconciler/src/ReactFiberHydrationContext.js:482:5)
          at updateHostComponent (packages/react-reconciler/src/ReactFiberBeginWork.js:1969:70)
          at beginWork (packages/react-reconciler/src/ReactFiberBeginWork.js:4369:14)
          at replayBeginWork (packages/react-reconciler/src/ReactFiberWorkLoop.js:3223:51)
          at replaySuspendedUnitOfWork (packages/react-reconciler/src/ReactFiberWorkLoop.js:3130:53)
          at renderRootConcurrent (packages/react-reconciler/src/ReactFiberWorkLoop.js:2895:17)
    
    Tests:       1 failed, 1 passed, 2 total
    

    The control it (same tree, no startTransition) stays green in both directions, which pins the failure to the time-sliced replay path.

    Form B: the assertConsoleErrorDev form

    Same file, with the last assertions of the first it replaced by the block below (and beforeEach pointing global.window / global.document / global.navigator / global.Node / global.addEventListener at the jsdom instance the way ReactDOMFloat-test.js does, otherwise the recoverable error surfaces as an uncaught jsdom error instead of a console.error):

        // The replayed host fiber re-claims from the stale cursor, the hydration
        // mismatch is reported, and the whole root is re-rendered on the client,
        // which is why `before` is logged a second time.
        await waitForAll(['before', 'after']);
        assertConsoleErrorDev([
          "Error: Hydration failed because the server rendered HTML didn't match the client. " +
            'As a result this tree will be regenerated on the client. This can happen if a SSR-ed Client Component used:\n\n' +
            "- A server/client branch `if (typeof window !== 'undefined')`.\n" +
            '- Variable input such as `Date.now()` or `Math.random()` which changes each ' +
            "time it's called.\n" +
            "- Date formatting in a user's locale which doesn't match the server.\n" +
            '- External changing data without sending a snapshot of it along with the HTML.\n' +
            '- Invalid HTML tag nesting.\n\n' +
            'It can also happen if the client has a browser extension installed which messes with the HTML before React loaded.\n\n' +
            'https://react.dev/link/hydration-mismatch\n\n' +
            '  <App lazyNode={{...}}>\n' +
            '    <div id="outer">\n' +
            '      <Before>\n' +
            '+     <div id="target">\n' +
            '-     <section id="child">\n' +
            '      ...\n' +
            '\n    in <stack>',
        ]);
    
        expect(container.querySelector('#target')).not.toBe(serverTarget);
        expect(container.querySelector('#child')).not.toBe(serverChild);
      });

    This one passes with the restore line removed (2 passed) and fails on unmodified main (before is 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 SuspendedOnImmediate and breaks out of the work loop, before its next slice. The test does not rely on a microtask for that. The React.lazy ctor logs read chunk at the moment it suspends, await waitFor(['before', 'read chunk']) stops SchedulerMock at that yield, then the test flips chunk.status to 'fulfilled' by hand and synchronously calls the then callback that lazyInitializer registered. The next slice sees isThenableResolved(thenable) and takes replaySuspendedUnitOfWork. Two things confirm it is the replay path rather than an unwind: before is not logged a second time (an unwind to the root re-renders the whole tree), and instrumenting replaySuspendedUnitOfWork to print unitOfWork.tag yields exactly one tag: 5.

    One coverage note: replayBeginWork restores the cursor only for HostComponent; HostSingleton falls through to the default branch. I probed that shape (hydrateRoot(document, ...) with the lazy node directly under <body>) and it hydrates correctly on main, and not vacuously: the same instrumentation shows it goes through replaySuspendedUnitOfWork with tag: 27. <body>'s stateNode comes from resolveSingletonInstance rather than from the cursor, so re-running beginWork does not depend on the cursor there.

    Happy to open a PR adding Form A as a regression test if that is useful.

  5. eps1lon commented on Sep 14, 2026

    @eps1lon
    Collaborator

    Thank you for digging. Glad to hear it's already fixed. We're not backporting bug fixes to prior SemVer minor releases.

  6. added a commit that references this issue on Oct 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Status: Unconfirmed

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions