react icon indicating copy to clipboard operation
react copied to clipboard

Bug: Suspense fallback remounts on hydration after use(browser()) + client use(promise)

Open michaltarasiuk opened this issue 2 months ago • 17 comments

On full page load, a client component calls use(browser()) (Suspense fallback is in the SSR HTML), then use() with a promise made on the client. On hydration the fallback remounts and the Progress animation starts again, even though loading is not done.

We hit this on /client-promise. Repro uses a client window.setTimeout promise after use(browser()). Real usage is the same shape when loading with Web APIs (for example localStorage, IndexedDB, or other window APIs).

/loading-only (same Progress, not a Suspense fallback) and /server-promise (promise from the server) do not restart.

Related earlier PR: https://github.com/react/react/pull/24236 (reverted in https://github.com/react/react/pull/24434).

React version: 19.3.0 (Next.js 16.3.4)

Steps To Reproduce

  1. Open https://suspense-fallback-hydration-reset.vercel.app/client-promise in the address bar (full page load).
  2. In DevTools: Disable cache, set CPU to 4x slowdown. Hard refresh. The Progress bar jumps back near hydration.
  3. Hard refresh https://suspense-fallback-hydration-reset.vercel.app/server-promise and https://suspense-fallback-hydration-reset.vercel.app/loading-only. The animation does not jump on those pages.

Link to code example:

https://suspense-fallback-hydration-reset.vercel.app/
https://github.com/michaltarasiuk/suspense-progress-hydration-reset

"use client";
import { use, Suspense } from "react";
import { browser } from "react-dom";

let p: Promise<number> | undefined;
function getClientPromise() {
  p ??= new Promise((r) => window.setTimeout(() => r(1), 3000));
  return p;
}

function ClientPromise() {
  use(browser());
  use(getClientPromise());
  return <div>Loaded</div>;
}

export default function Page() {
  return (
    <Suspense fallback={<Loading />}>
      <ClientPromise />
    </Suspense>
  );
}

The current behavior

The SSR fallback remounts on hydration. The Progress animation starts again.

The expected behavior

The SSR fallback stays mounted on hydration. The animation runs without restart until loading finishes.

michaltarasiuk avatar Sep 13 '26 15:09 michaltarasiuk

The browser() docs describe this same path for a Suspense-enabled data-fetching library:

function useBrowserQuery(query, options) {
  if (options.initialData === undefined) {
    use(browser('useBrowserQuery: No initial data was provided.'));
  }

  return useQuery(query, options);
}

From the docs: with initialData, React renders on the server; without it, React leaves the closest Suspense fallback in the HTML. In the browser, useQuery can fetch the data or read it from its client cache. https://react.dev/reference/react-dom/browser#conditionally-rendering-on-the-server

This repro uses a cached window.setTimeout promise in place of that client fetch, only to keep the demo small. The sequence is the same: the SSR fallback is already painted, hydration runs, the boundary suspends again on the client, and the fallback remounts.

michaltarasiuk avatar Sep 13 '26 16:09 michaltarasiuk

🚀 Bounty Alert!

💰 A bounty of $100.00 has been created by devlootxyz-bounties on BountyHub for this issue.

🔗 Claim this bounty by submitting a pull request that solves this issue!

You can also increase the amount of the bounty if you think the issue is worth more.

Good luck, and happy coding! 💻

bountyhub-bot avatar Sep 15 '26 21:09 bountyhub-bot

Root Cause Analysis

The fallback remounting occurs due to how React transitions a dehydrated Suspense boundary from server-rendered fallback mode to client retry mode when primary children suspend during hydration retry.

1. Server Phase (Fizz)

  • When a component calls use(browser()) during SSR, ReactFizzHooks throws a recoverable error branded with REACT_RECOVERABLE_TYPE.
  • The parent <Suspense> boundary catches this error and outputs a dehydrated fallback boundary marked with REACT_RECOVERABLE_DIGEST (<!--$!--><template data-dgst=""></template>...fallback markup...<!--/$-->).
  • In the browser, the server-rendered fallback DOM is visible and animations begin immediately.

2. Initial Hydration Pass

  • During initial hydration, mountDehydratedSuspenseComponent checks isSuspenseInstanceFallback(suspenseInstance).
  • Because the boundary is in a fallback state, React attaches memoizedState = { dehydrated: suspenseInstance, ... } and schedules a DefaultLane update to retry rendering the primary tree on the client.
  • The server fallback DOM remains untouched in the document.

3. Hydration Retry Pass (retrySuspenseComponentWithoutHydrating)

  • When the DefaultLane task runs, updateDehydratedSuspenseComponent sees isSuspenseInstanceFallback(...) and invokes retrySuspenseComponentWithoutHydrating:
    1. It reconciles deletions on current.child (the fiber pointing to the dehydrated fallback DOM).
    2. It sets workInProgress.memoizedState = null to indicate that this boundary is no longer dehydrated.
    3. It begins rendering the primary children (mountSuspensePrimaryChildren).

4. The Client Suspend & Second Pass Remount

  • When rendering <ClientPromise />:

    • use(browser()) returns undefined (safe no-op on the client).
    • use(getClientPromise()) suspends on the client promise.
  • React catches the suspended promise and enters the second pass in updateDehydratedSuspenseComponent:

    } else if ((workInProgress.memoizedState as null | SuspenseState) !== null) {
      // Leave the existing dehydrated child in place
      workInProgress.child = current.child;
      workInProgress.flags |= DidCapture;
      return null;
    } else {
      // Suspended, but memoizedState was set to null in step 3!
      mountSuspenseFallbackAfterRetryWithoutHydrating(
        current,
        workInProgress,
        nextPrimaryChildren,
        nextFallbackChildren,
        renderLanes,
      );
      ...
    }
    

Yeshwanth-develops avatar Sep 16 '26 04:09 Yeshwanth-develops

Hi @michaltarasiuk ,

I’d like to work on this bounty. I’ve reviewed the reproduction steps and understand that the issue is related to the Suspense fallback being remounted during hydration when a client component first suspends with use(browser()) and then suspends on a client-created promise.

I’ll investigate the hydration/Suspense behavior, reproduce the issue against the relevant React version, identify the cause, and implement a focused fix with appropriate regression coverage. I’ll also verify the behavior against the existing /client-promise, /server-promise, and /loading-only cases to make sure the fix doesn’t introduce regressions.

I’ll do the implementation and debugging myself, using AI only as an assistance tool where appropriate, in accordance with the bounty requirements.

I’m interested in taking this up. Please let me know if there are any additional constraints or preferred testing requirements.

vidhi-0205 avatar Sep 16 '26 13:09 vidhi-0205

Hi @vidhi-0205, I didn't report the bounty.

michaltarasiuk avatar Sep 16 '26 16:09 michaltarasiuk

Hey @michaltarasiuk is this issue currently opens up ? I would like like to work on this issue please /assign it to me thanks !!

ayushman1210 avatar Sep 24 '26 13:09 ayushman1210

/claim

Claiming the $100 BountyHub bounty as theworker02.

Plan:

  1. Reproduce the /client-promise hydration remount against current main (use(browser()) then client-created use(promise)).
  2. Trace dehydrated Suspense fallback handling in the hydration retry path (related history: #24236 / #24434).
  3. Preserve the SSR fallback DOM across a client re-suspend instead of deleting and remounting an identical fallback, so CSS animations/DOM state survive.
  4. Add a focused regression test and open a PR referencing #37620.

theworker02 avatar Sep 26 '26 16:09 theworker02

Opened PR with the fix + regression coverage: https://github.com/react/react/pull/37694

Verified locally: yarn test ReactDOMFizzServer-test (browser-only / remount patterns) - 7 passed.

theworker02 avatar Sep 26 '26 16:09 theworker02

/claim

Claiming the $100 BountyHub bounty as sidshehria.

Opened PR with the fix + regression coverage: https://github.com/react/react/pull/37705

Verified locally: yarn test --build=false ReactDOMFizzServer-test (browser-only / remount patterns) — 7 passed.

sidshehria avatar Sep 28 '26 16:09 sidshehria

Hi, I'm interested in contributing a fix for this issue.

Before I start working on it, could you please clarify whether the $100 BountyHub bounty is active and what the eligibility and payout requirements are?

I also noticed existing related PRs. Could you confirm whether a new contribution is still needed and what specific work remains?

Thank you!

I claim this $100 bounty! Will fix the Suspense hydration fallback remount bug and submit PR within 72h.

1132dadf avatar Oct 18 '26 14:10 1132dadf

Claiming the $100 BountyHub bounty.

Opened a fix: #37966 — Preserve painted SSR fallback DOM when hydration suspends again on a recoverable boundary.

Key points vs. the root cause:

  • Hydration retry deletes the server-painted DehydratedFragment fallback and mounts an identical client-rendered fallback, restarting CSS-driven animations (and in some orderings hands raw tag 18 to the work loop → Unknown unit of work tag (18)).
  • This fix keeps the painted fallback mounted (un-queues the deletion), renders the primary children into a hidden offscreen so the boundary can complete when the client data resolves, and reattaches the preserved fragment wherever the clone/begin path would previously surface tag 18. Three small hunks in ReactFiberBeginWork.js.

Evidence: new end-to-end test — SSR paints the fallback, hydration suspends on both a browser() resource and a client promise, the fallback DOM node keeps its identity throughout, and content swaps in after the promise resolves. Full suite (185/185) + reconciler Suspense suites + Flow pass; competitors' crash path (Unknown unit of work tag (18)) is covered by the same suite.

Wallet for the bounty payout (Base USDC): 0xbbe6966949d7265a7f5f0b793f08293b9b7fe926

9xj89gzrtw-hue avatar Oct 22 '26 18:10 9xj89gzrtw-hue

/claim

Claiming the BountyHub bounty as MilindChatrabhuji.

Fix submitted in PR #38026: https://github.com/react/react/pull/38026 (branch ix/suspense-fallback-hydration-remount-37620).

Root Cause & Implementation Summary

When a Suspense boundary outputs a recoverable fallback during SSR (e.g. use(ReactDOM.browser()) bailout with REACT_RECOVERABLE_DIGEST), the server-rendered fallback DOM is painted and visible. If the component subsequently suspends again on the client (e.g. use(clientPromise)), the previous hydration retry fell through to mountSuspenseFallbackAfterRetryWithoutHydrating, deleting the painted DehydratedFragment fallback fiber and mounting a new client fallback, which resets DOM state and restarts CSS spinner animations.

PR #38026 resolves this cleanly:

  1. In updateDehydratedSuspenseComponent (restart path), un-queues the deletion of DehydratedFragment, mounts primary children into a hidden Offscreen fiber (mode: 'hidden'), re-attaches the preserved fallback, sets SUSPENDED_MARKER, and returns ull.
  2. Preserves the fragment across parent clone passes without exposing raw tag 18 to the work loop.
  3. Added end-to-end regression tests in ReactDOMFizzServer-test.js validating that the server-painted fallback DOM node retains its exact identity across client re-suspension and successfully resolves without unmounting/remounting.

MilindChatrabhuji avatar Oct 28 '26 12:10 MilindChatrabhuji

Hi, please stop claiming the bounty. I am not the creator of it. Also, stop creating multiple duplicate, AI-generated PRs.

michaltarasiuk avatar Oct 28 '26 12:10 michaltarasiuk

l know

---- 回复的原邮件 ---- | 发件人 | @.> | | 日期 | 2026年10月28日 20:32 | | 收件人 | @.> | | 抄送至 | @.>@.> | | 主题 | Re: [react/react] Bug: Suspense fallback remounts on hydration after use(browser()) + client use(promise) (Issue #37620) | michaltarasiuk left a comment (react/react#37620)

Hi, please stop claiming the bounty. I am not the creator of it. Also, stop creating multiple duplicate, AI-generated PRs.

— Reply to this email directly, view it on GitHub, or unsubscribe. Triage notifications, keep track of coding agent tasks and review pull requests on the go with GitHub Mobile for iOS and Android. Download it today! You are receiving this because you commented.Message ID: @.***>

1132dadf avatar Oct 28 '26 12:10 1132dadf

@devlootxyz-bounties I looked into this and opened #38174, which adds tests only (no fix). Findings, in case they help triage:

Confirmed, and not specific to browser(). A <!--$!--> boundary is retried as a client render during hydration. If that retry suspends, updateDehydratedSuspenseComponent calls mountSuspenseFallbackAfterRetryWithoutHydrating, which deletes the server fallback and inserts a new one. On main (b05c0b75f), the fallback node gets replaced in all three cases that produce a client-rendered boundary:

  • use(browser()) followed by a client suspend (this issue)
  • abort(browser()) followed by a client suspend (the timeout example in the browser() docs)
  • a server error followed by a client suspend

This is the behavior #24236 changed in 2022 and #24434 reverted. The revert was for a late-mutations regression at Meta, cause unknown. #24236's tests are still on main as @gate FIXME in ReactDOMFizzServer-test.js: "does not recreate the fallback if server errors and hydration suspends" and the two tests after it. So the expected behavior is already specified. What's missing is a fix that doesn't bring back that regression. #38174 adds the browser() version of that @gate FIXME test, plus a passing test that new fallback props still render while the client retry is suspended.

Repro measurements. Headless Chrome 157, cache disabled, React 19.3.0-canary-cbb046ab-20260731 (the version Next 16.3.4 bundles). I used a MutationObserver installed before any page script ran.

  • /client-promise: during hydration the SSR [role=progressbar] node is removed and a new node is inserted. At 20x CPU slowdown, the indicator's animation currentTime drops from 717 ms to 0.
  • /server-promise: the SSR node stays until the content arrives.
  • /loading-only: the SSR node is never replaced.

Open PRs. #37705 is line-for-line identical to #37694, and #38026 to #37966. I applied each distinct patch on main. Both keep the server fallback node in the two browser() cases above, but:

  • They only do it when the digest is the browser() digest, so the server-error case is unchanged and the @gate FIXME tests still fail.
  • The kept fallback is never hydrated, so its event handlers don't fire. A <button onClick> in the fallback gets 0 calls (1 on main).
  • Changes to the fallback prop while suspended are ignored. The fallback keeps showing "Loading..." where main renders the new text. This is the case the third FIXME test covers.

Possible workaround until this is fixed. Move the indicator out of the boundary, so it hydrates as normal content, and give the boundary an empty fallback:

"use client";

function ClientData({ onReady }: { onReady: () => void }) {
  use(browser());
  use(getClientPromise());
  useLayoutEffect(onReady, [onReady]);
  return <Loaded />;
}

export function ClientPromiseWithStableLoading() {
  const [ready, setReady] = useState(false);
  const onReady = useCallback(() => setReady(true), []);
  return (
    <>
      {ready ? null : <Loading />}
      <Suspense fallback={null}>
        <ClientData onReady={onReady} />
      </Suspense>
    </>
  );
}

In a React DOM test on main, the server-rendered indicator keeps the same DOM node through hydration, no recoverable errors are reported, and the indicator is removed once the content mounts. I haven't run it in your Next app.

transmogrify-cell avatar Nov 09 '26 20:11 transmogrify-cell

Update: #38174 now has a fix on top of the tests.

If the client render of a <!--$!--> boundary suspends on data and the boundary hasn't received new props or a context change, it stays dehydrated and keeps the server fallback until the data resolves, instead of mounting a new one. That covers browser(), abort() and server errors. It's scoped to the boundary, so unlike #24236 it doesn't hold back the root's commit. The server error is still reported at the same point as before, and only once.

Two limitations:

  • The kept fallback isn't hydrated, so its event handlers don't run until the content arrives, same as a fallback that's still streaming.
  • An update that gives the boundary new props while it's waiting still recreates the fallback once.

Two of the old @gate FIXME tests from #24236 pass now. The transition one stays gated, since I didn't want to block transitions until client data loads. I haven't been able to run it in your Next app, so if you get a chance to try it against your repro, I'd like to hear how it goes.

transmogrify-cell avatar Nov 10 '26 21:11 transmogrify-cell