fix(react-router): preserve lazy promise for React use() #8549
main fromrefs/pull/8549/head·opened issue: #8487
🎯 Changes#
✅ Checklist#
- I have followed the steps in the Contributing guide.
- I have tested code changes locally with the relevant test commands, or tests do not apply to this pull request.
- I fully understand the code in this pull request, including any code generated with AI assistance.
🚀 Release Impact#
- This change affects published code, and I have generated a changeset.
- This change is docs/CI/dev-only (no release).
Summary by CodeRabbit#
- Bug Fixes
- Lazy-loaded routes now retain successfully loaded modules for reuse, avoiding repeated loading work when those routes are accessed again. Route components also continue to participate in the app’s loading flow after their component has loaded, improving consistency when navigating between lazy-loaded routes.
- 1
Navigate logical layers of code changes, visualize relationships, and explore their blast radius.
No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
⚙️ Run configuration
Configuration used: Repository: TanStack/router/.coderabbit.yaml
Review profile: CHILL
Plan: Advanced
Run ID:
b8b922f9-c269-47bc-a647-5a1fabe018e5📥 Commits
Reviewing files that changed from the base of the PR and between 41ebd288677beacb8eb56953f5f8c26e9d33313e and 6355bbee3f948a61a77bd23e57e0c7bc2932478e.
📒 Files selected for processing (1)
packages/react-router/src/lazyRouteComponent.tsx
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.
📝 Walkthrough
Walkthrough#
The lazy route component now retains the resolved import promise and preload function. Its loading path calls
reactUse(load())when available, and only throws the loading promise whenreactUseis unavailable and the component is unset.Changes#
Lazy route loading
Layer / File(s) Summary Import caching and component loading
packages/react-router/src/lazyRouteComponent.tsxThe resolved import promise and preload function remain available. When reactUseexists, the component callsreactUse(load()); otherwise, it throws the loading promise only while the component is unset.Priority: ⬇️ Low
Estimated code review effort: 2 (Simple) | ~8 minutes
Change: Bug fix
Suggested reviewers:
sheraffMerge Risk: ⚪ Minimal · up to
6355bNo actionable issue is established in this change; it appears ready to merge subject to normal checks.
Architecture Summary#
Architecture risk: 🟡 Medium · up to
6355bThe change affects 1 system.
Changed systems:
packages/react-routerArchitecture concerns No architecture-level concerns identified.
Review details
Systems and components
- observed — packages/react-router (library) was modified; 1 changed file maps to changed impact.
Before / after behavior
- observed — Modified behavior in packages/react-router/src/lazyRouteComponent.tsx: After a client-side import resolves, the code no longer clears
loadPromiseor removeslazyComp.preload; the resolved promise remains cached and preload remains available. - observed — Modified behavior in packages/react-router/src/lazyRouteComponent.tsx:
reactUse(load())now runs wheneverreactUseexists, rather than only whencompis unset. WhenreactUseis absent,load()is thrown only ifcompis unset.
Reliability and maintainability
- inferred — Risk-relevant change factors for packages/react-router: blast_radius_1; direct_dependents_1
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)#
Check name Status Explanation Resolution Description check ⚠️ Warning The checklist is complete, but the Changes section contains no description of the implementation or motivation. The Release Impact section also leaves both options unchecked, although the change affec… Describe the implementation and motivation in the Changes section. Confirm the release impact and add a changeset if the published package requires one. ✅ Passed checks (4 passed)
Check name Status Explanation Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 1 functions across 1 files. Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request. Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request. Title check ✅ Passed The title clearly identifies the primary change: preserving the lazy promise for React use(). Full details: Description check
Explanation
The checklist is complete, but the Changes section contains no description of the implementation or motivation. The Release Impact section also leaves both options unchecked, although the change affects published code.
- Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
- Create a new PR
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Comment `@coderabbitai help` to get the list of available commands.We hit this too, in a Vite + React SPA on
@tanstack/react-router1.170.36 withreact/react-dom19.3.0. The warning shows on our/loginpage on every cold load. That page is alazyRouteComponentrendered inside a route'scomponent, so the router never calls.preload()on it and it always suspends on first mount. The stack ends atLazy→React.use→trackUsedThenable. 1.170.40 has the same code.Until this lands we've replaced
lazyRouteComponentwith a local helper that follows the same approach as this PR:- it calls
use()on every render; - it keeps the resolved promise instead of clearing it;
- it sets
status = 'fulfilled'/valueon the promise itself when the import settles, so a chunk the router preloaded renders on the first pass without suspending.
With that in place the warning is gone. We checked 3/3 cold loads before and after, against the same backend, plus client-side navigation across ~45 lazy routes.
In case it helps with a regression test: we could reproduce it deterministically in Vitest/jsdom, but only with the transition timing from #8487. A transition mounts the lazy component, it suspends while old content stays visible, then the chunk resolves and a second transition lands in the same tick. Wrap each step in
await act(async () => …). A plain<Suspense>mount does not reproduce it. Also note that React logs this warning only once per module instance, so any test that expects it has to be the first in its file to see it.Thanks for the fix. We'll switch back to
lazyRouteComponentonce it's released.- it calls
We have shipped this change as a backport on
@tanstack/react-router1.170.44 with React 19.3, and found one side effect worth folding into this PR.Keeping the resolved
loadPromiseand always callinguse(load())makes a lazily split component suspend once on its first render, even when the router already loaded its chunk. One example is a route'spendingComponent, whichloadComponentsresolves beforeonPendingReady. React has never seen that promise, souse()treats it as pending, and the nearest outer<Suspense>fallback renders before the component does. In our app, the first visit to each code-split page showed the layout's generic skeleton instead of the route's own pending component.Minimal repro:
const Lazy = lazyRouteComponent(() => Promise.resolve({ default: () => <p>pending shape</p> })); await Lazy.preload?.(); let fallbackRenders = 0; const Fallback = () => { fallbackRenders += 1; return <p>outer fallback</p>; }; // render inside act(): // <Suspense fallback={<Fallback />}><Lazy /></Suspense> // expected: fallbackRenders === 0; with this PR as is: 1What fixed it for us was marking the kept promise settled when the import resolves, so
use()returns synchronously for an already loaded chunk:loadPromise = importer() .then((res) => { // ... comp = res[exportName ?? "default"]; Object.assign(loadPromise!, { status: "fulfilled", value: undefined }); }) .catch(/* unchanged */);The rejection path is unchanged; it still resets
loadPromiseso a later render retries.
Sign in to join this conversation.
copilot-pull-request-reviewer[bot](GitHub profile, opens in a new tab) reviewed
Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.