fix(react-query): hydrate deferred queries before observers subscribe to avoid a redundant refetch #11137
main fromrefs/pull/11137/head·opened 🎯 Changes#
Fixes #9610.
HydrationBoundary defers hydration of queries that already exist in the cache to an effect, so that transitions don't update existing observers mid-render. But useQuery's useSyncExternalStore subscription is also a passive effect, and children's effects run before parents'. On a revisit, where the query is cached but was unmounted, the observer subscribes first, sees the old stale entry and starts a refetch of the exact data the dehydrated state already contains. The server computes it in the loader and the client immediately fetches it again.
This moves the deferred hydration, and the optionsRef sync it reads, to a layout effect. All layout effects run before any passive effect, so hydration lands in the cache before a remounting observer decides whether to fetch. Layout effects still only run when the tree commits, so the aborted transition behaviour is unchanged and its test stays green.
Behaviour change worth noting: already-mounted observers now get hydrated data at commit time rather than after paint. One timing assertion in an existing test was updated for that. The render phase guarantee is still covered by the aborted transition test.
I tried a narrower version that only hydrates queries with no subscribers, so mounted observers keep their old timing. It doesn't work here: React cleans up a deleted subtree's subscriptions in the passive phase, after this layout effect, so when a page unmounts and remounts in the same commit the outgoing observer is still on the query and the refetch comes back. There's a test for that case now.
Verified with tests that fail on main and pass with the fix, plus a jsdom repro of the React Router loader flow from the issue against the built package.
Not covered: a useSuspenseQuery over a query that is in pending state with no data starts its fetch during render, before any layout effect. That pre-existing path is unaffected by this change.
✅ Checklist#
- I have followed the steps in the Contributing guide.
- I have tested this code locally with
pnpm run test:pr.
🚀 Release Impact#
- This change affects published code, and I have generated a changeset.
- This change is docs/CI/dev-only (no release).
🤖 Generated with Claude Code
Summary by CodeRabbit#
- Bug Fixes
- Improved hydration timing so deferred query data is available before effects run.
- Prevented remounted queries from unnecessarily refetching data already present in dehydrated state.
- Preserved correct behavior for stale and inactive queries during hydration.
- 1
ostapondo(GitHub profile, opens in a new tab) changed the title
Updated after review feedback on #11157.
Before, this moved the whole queue to a layout effect, existing queries included, which also changed when already-mounted observers see hydrated data (commit time instead of after paint) and needed one assertion in an existing test to be relaxed. Only the unobserved half needs to move to fix the refetch, so that's all it does now. The test file is additions only, nothing existing changed, and "Existing observer should not have updated at this point" keeps guarding the observed case.
Same shape in #11157 now.
ostapondo(GitHub profile, opens in a new tab) changed the title
Rolled the split back out of this one, it doesn't hold up in React.
React cleans up a removed subtree's subscriptions in the passive phase, after this layout effect runs. So when a page unmounts and remounts in the same commit, which is what happens as soon as the boundary wraps the page, the outgoing observer is still counted on the query, the split skips it and the refetch is back. Added a test for that shape, it fails with the split and passes with this.
So this is back to hydrating the whole queue in the layout effect, which is fine here because React never commits a render it throws away.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. Inline comments: In `@packages/react-query/src/__tests__/HydrationBoundary.test.tsx`: - Around line 152-160: Update the HydrationBoundary test’s existing-observer assertions so the prior value remains visible during render, and only the hydrated value appears after passive effects flush. Keep the immediate “added” assertion for newly introduced query data, then advance timers and assert the existing query changes to “should change” afterward.🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID:
3bd29617-79dc-47a3-a8a6-86fe60bd2a2c📥 Commits
Reviewing files that changed from the base of the PR and between fe46639ce1710546b62160b570c1b4daa6032080 and fca2f4cbad611e2fd48f6da18ba59d5121fd62a9.
📒 Files selected for processing (3)
.changeset/hungry-planes-tease.mdpackages/react-query/src/HydrationBoundary.tsxpackages/react-query/src/__tests__/HydrationBoundary.test.tsx
🚧 Files skipped from review as they are similar to previous changes (2)
- .changeset/hungry-planes-tease.md
- packages/react-query/src/HydrationBoundary.tsx
@@ -149,11 +149,12 @@149149 </QueryClientProvider>,150150 )151151152- // Existing observer should not have updated at this point,153- // as that would indicate a side effect in the render phase154- expect(rendered.getByText('string')).toBeInTheDocument()152+ // The existing observer picks up the hydrated data once effects have153+ // flushed, but not during the render phase (the aborted transition154+ // test guards the render phase)155+ expect(rendered.getByText('should change')).toBeInTheDocument()155156 // New query data should be available immediately156157 expect(rendered.getByText('added')).toBeInTheDocument()157158158159 await vi.advanceTimersByTimeAsync(0)159- // After effects phase has had time to run, the observer should have updated160+ // Nothing changes after the effects phase has had time to run🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Preserve passive hydration for existing observers.
Line 155 accepts hydrated existing-query data before the effects phase. This permits a regression where
HydrationBoundaryhydrates observed queries in its layout effect. Restore the assertion that the existing observer retains its prior value until effects flush, then assert the hydrated value.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/react-query/src/__tests__/HydrationBoundary.test.tsx` around lines 152 - 160, Update the HydrationBoundary test’s existing-observer assertions so the prior value remains visible during render, and only the hydrated value appears after passive effects flush. Keep the immediate “added” assertion for newly introduced query data, then advance timers and assert the existing query changes to “should change” afterward.✅ Addressed in commit ab12b64
That assertion is the change, not a regression it permits. Hydrating in a layout effect means an observed query has the data at commit, so it's already there by that line. Keeping the old expectation means keeping the passive effect, which is the bug being fixed.
I did try the narrower version where only queries with no subscribers move to the layout effect, so mounted observers keep their old timing. React cleans up a removed subtree's subscriptions in the passive phase, after this layout effect, so a page that unmounts and remounts in the same commit still has its old observer on the query and the refetch comes back. There's a test for that shape now.
Render phase purity is unchanged, the aborted transition test still guards it.
@ostapondo, you are correct. I withdraw this finding.The layout effect must update the query before the remounted observer can trigger
refetchOnMount. Keeping passive hydration for this case would reintroduce the duplicate refetch.The aborted-transition test still protects render-phase purity. The same-commit remount test covers the subscription-cleanup timing that the original finding missed.
🐇💭
You are interacting with an AI system.✏️ Learnings added
Learnt from: ostapondo Repo: TanStack/query PR: 11137 File: packages/react-query/src/__tests__/HydrationBoundary.test.tsx:0-0 Timestamp: 2026-08-09T18:09:07.920Z Learning: In `packages/react-query/src/HydrationBoundary.tsx`, queued hydration must run in a layout effect before a `useQuery` observer remounted in the same React commit subscribes. React cleans up the removed subtree's query subscription in the passive phase, so an observer-only split based on current subscribers can retain a stale observer and reintroduce `refetchOnMount`. The aborted-transition test in `packages/react-query/src/__tests__/HydrationBoundary.test.tsx` guards against render-phase hydration.Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.
ostapondo(GitHub profile, opens in a new tab)replied on
packages/react-query/src/__tests__/HydrationBoundary.test.tsxlines 152 to 160That assertion is the change, not a regression it permits. Hydrating in a layout effect means an observed query has the data at commit, so it's already there by that line. Keeping the old expectation means keeping the passive effect, which is the bug being fixed.
I did try the narrower version where only queries with no subscribers move to the layout effect, so mounted observers keep their old timing. React cleans up a removed subtree's subscriptions in the passive phase, after this layout effect, so a page that unmounts and remounts in the same commit still has its old observer on the query and the refetch comes back. There's a test for that shape now.
Render phase purity is unchanged, the aborted transition test still guards it.
coderabbitai[bot](GitHub profile, opens in a new tab)replied on
packages/react-query/src/__tests__/HydrationBoundary.test.tsxlines 152 to 160@ostapondo, you are correct. I withdraw this finding.The layout effect must update the query before the remounted observer can trigger
refetchOnMount. Keeping passive hydration for this case would reintroduce the duplicate refetch.The aborted-transition test still protects render-phase purity. The same-commit remount test covers the subscription-cleanup timing that the original finding missed.
🐇💭
You are interacting with an AI system.✏️ Learnings added
Learnt from: ostapondo Repo: TanStack/query PR: 11137 File: packages/react-query/src/__tests__/HydrationBoundary.test.tsx:0-0 Timestamp: 2026-08-09T18:09:07.920Z Learning: In `packages/react-query/src/HydrationBoundary.tsx`, queued hydration must run in a layout effect before a `useQuery` observer remounted in the same React commit subscribes. React cleans up the removed subtree's query subscription in the passive phase, so an observer-only split based on current subscribers can retain a stale observer and reintroduce `refetchOnMount`. The aborted-transition test in `packages/react-query/src/__tests__/HydrationBoundary.test.tsx` guards against render-phase hydration.Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.
ostapondo(GitHub profile, opens in a new tab) linked this to fix #9610
Sign in to join this conversation.
Note
Reviews paused#
It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the
reviews.auto_review.auto_pause_after_reviewed_commitssetting.Use the following commands to manage reviews:
@coderabbitai resumeto resume automatic reviews.@coderabbitai reviewto trigger a single review.Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID:
a708d21a-baff-416f-8302-0783a50a5868📥 Commits
Reviewing files that changed from the base of the PR and between fca2f4cbad611e2fd48f6da18ba59d5121fd62a9 and ab12b643e5d64f39509c85929028788e51bd8d9a.
📒 Files selected for processing (1)
packages/react-query/src/__tests__/HydrationBoundary.test.tsx🚧 Files skipped from review as they are similar to previous changes (1)
📝 Walkthrough
Walkthrough#
HydrationBoundarynow hydrates deferred queries in an isomorphic layout effect. Tests verify immediate hydrated data and prevent redundant refetches when queries remount.Changes#
HydrationBoundary hydration timing
packages/react-query/src/HydrationBoundary.tsxHydrationBoundaryusesuseLayoutEffectin the browser anduseEffecton the server. Queued hydration runs after commit and before children’s passive subscriptions.packages/react-query/src/__tests__/HydrationBoundary.test.tsx,.changeset/hungry-planes-tease.mdEstimated code review effort: 3 (Moderate) | ~20 minutes
Possibly related issues
HydrationBoundary.Possibly related PRs
Sequence Diagram(s)#
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
#9610by hydrating before remounted observers can trigger a duplicate refetch.✨ Finishing Touches
🧪 Generate unit tests (beta)
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.
❤️ Share