fix(preact-query): hydrate unobserved queries before observers subscribe to avoid a redundant refetch #11157
main fromrefs/pull/11157/head·opened 🎯 Changes#
Fixes #11155.
HydrationBoundary waits until after render to hydrate queries that are already
cached, so a render that never commits can't change what's on screen. But
useSyncExternalStore subscribes from a passive effect too, and child effects
run before the parent's. So on a revisit — query cached, page unmounted — the
observer gets there first, reads the stale entry, and refetches the exact data
the dehydrated state is already carrying.
Same race as #11137 on the react-query side, but that fix doesn't port over. React never commits a render that suspends; preact does. It diffs, commits, runs layout effects, then swaps in the fallback. So moving the whole queue to a layout effect would let a route that suspends and never arrives overwrite data a sibling is still showing.
Hence only part of it moves: queries nobody is observing when the boundary renders hydrate in a layout effect, the rest keep waiting. Nothing can be rendering a query with no observers, so hydrating one early can't change what's on screen — the whole reason existing queries wait. And it lands before a remounting observer subscribes, which is what kills the refetch.
No isServer branch on the layout effect: preact-render-to-string sets
options._skipEffects, which skips useLayoutEffect and useEffect alike. The
useSyncExternalStore shim here already calls useLayoutEffect unconditionally
for the same reason.
Tests#
- new — a cached but unmounted query isn't refetched when the hydrated data is fresh. Fails on main.
- new — a query on screen is left alone while a sibling suspends. Passes on main, fails if you move the whole queue instead.
- changed —
should hydrate new but not existing queries if transition is aborted. Its rerender introduces a new root, so preact remounts everything and the observer is gone before the boundary renders. The query is now indistinguishable from one nobody watches, so it asserts the data does land — the sibling test above covers what it was protecting.
✅ 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 behavior for inactive queries, making hydrated data available immediately after a component commits.
- Prevented unnecessary refetches when queries remount after hydration.
- Preserved fresh on-screen query data when sibling content suspends or transitions are interrupted.
- Improved recovery after suspended transitions so previously hydrated data remains available.
- Preserved cached data while the application is restoring, avoiding unnecessary data loss or reloads.
- Prevented duplicate hydration of identical queries.
- 1
This is the preact-query counterpart of #11137, and it takes a meaningfully different approach worth flagging rather than just mirroring it.
#11137 moves the whole
hydrationQueueinto a layout effect, existing queries included, regardless of whether anything is currently observing them. Looking at that PR's own test diff, the assertion for an on-screen existing query changed from "should not have updated at this point" (render phase) to expecting the text to already show the hydrated value right after render, since layout effects flush synchronously before the test's next assertion. That's a behavior change for observed queries too, not just the unobserved ones the bug report was actually about.This PR keeps that distinction instead: only queries with zero observers move to
useLayoutEffect(theunobservedhalf ofHydrationQueue), existing queries that are actually on screen still wait for the passiveuseEffect, same as before. The new "should not hydrate a query that is on screen while a sibling suspends" test locks that in, an observed query stays untouched while a sibling boundary is still suspended. That matches the original comment in this file about not wanting to surprise users with updates to state that's currently rendered, which #11137's version seems to relax for react-query.Not sure which one is intentional. If preact-query is supposed to track react-query's behavior 1:1, this is worth reconciling one way or the other, either #11137 needs the same observed/unobserved split, or this PR is doing more than the reported bug strictly needs. Either way, the mechanism in this PR is correct for what it does,
getObserversCount() === 0is the right check and the layout effect ordering argument in the comments holds up against how passive effects flush in child-before-parent order.Good catch, and you're right about what #11137 does to observed queries.
The two differ because React and Preact don't agree on what a suspended render is. React never commits one, so in #11137 the layout effect simply doesn't run for a render that gets thrown away, React keeps that guarantee for us. Preact commits the tree, runs the layout effects and only then swaps in the fallback, so moving the whole queue there lets a route that suspends and never arrives overwrite data a sibling is still showing on screen. That's what the sidebar test locks in.
So I'd reconcile it the other way round and put the same split in #11137. I tried that on the branch: applied the observed/unobserved split and reverted the test file back to what's on main, keeping only the new inactive-query test. The whole file passes as is, 13 tests, nothing else touched. The existing assertions stay, including "Existing observer should not have updated at this point" and the aborted transition one, and the timing change for observed queries you pointed at goes away, they keep updating after paint like before.
Pushing that to #11137 now, then both packages have the same shape and the bug fix is the only behavior that changes.
Pushed to #11137, both are the same shape now: the observer check moved into the layout effect in this one too, so the memo stays untouched and the diff is just the two effects.
In react-query the split needed no test changes at all, the file is additions only.
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/preact-query/src/HydrationBoundary.tsx`: - Around line 120-122: Prevent duplicate hydration retryers by deduplicating query hashes between the layout and passive hydration passes in HydrationBoundary, or equivalently within hydrate. Ensure an unobserved existing query with an already-rejected initialPromise is hydrated through only one retry path, and add a regression test covering this scenario.🪄 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:
295aec3e-8c85-435f-a108-6d472284e6ad📥 Commits
Reviewing files that changed from the base of the PR and between f17d36370b9320e0a1b4df87fd17aaf3a6e07a6c and c975625232ac126cb26e00a3f00032d9b266394a.
📒 Files selected for processing (1)
packages/preact-query/src/HydrationBoundary.tsx
@@ -99,3 +102,21 @@99102 return undefined100103 }, [client, state])101104105+ // Waiting for a passive effect is too late for a query nobody is observing.106+ // Children subscribe to the cache from their own passive effects and those107+ // run before the parent's, so a query that remounts under this boundary reads108+ // the old entry, finds it stale and refetches the very data we are holding.109+ // Nothing is rendering these queries, so hydrating them as the tree commits110+ // cannot change anything on screen, which is the only reason existing queries111+ // wait in the first place.112+ useLayoutEffect(() => {113+ if (hydrationQueue) {114+ const queryCache = client.getQueryCache()115+ const unobserved = hydrationQueue.filter((dehydratedQuery) => {116+ const query = queryCache.get(dehydratedQuery.queryHash)117+ return !query || query.getObserversCount() === 0118+ })119+120+ if (unobserved.length > 0) {121+ hydrate(client, { queries: unobserved }, optionsRef.current)122+ }🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash set -euo pipefail rg -n -C 8 \ 'hydrate\(client, \{ queries: (unobserved|hydrationQueue) \}' \ packages/preact-query/src/HydrationBoundary.tsx rg -n -C 8 \ 'dehydratedAt > query\.state\.dataUpdatedAt|initialPromise|onError|onSettled|fetchStatus: .idle.' \ packages/query-core/srcRepository: TanStack/query
Length of output: 50371
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "== HydrationBoundary relevant lines ==" sed -n '1,170p' packages/preact-query/src/HydrationBoundary.tsx echo _echo "== query.fetch relevant dispatch/fetch/reject path ==" sed -n '480,640p' packages/query-core/src/query.ts echo "== queryCache dispatch/cache error callbacks ==" sed -n '1,180p' packages/query-core/src/queryCache.ts echo echo "== Retryer resolve/fail dispatch behavior around completed status ==" sed -n '130,230p' packages/query-core/src/retryer.ts echo echo "== hydration.ts hydration path details ==" sed -n '200,330p' packages/query-core/src/hydration.tsRepository: TanStack/query
Length of output: 5548
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "== query.fetch relevant dispatch/fetch/reject path ==" sed -n '480,640p' packages/query-core/src/query.ts echo "== queryCache dispatch/cache error callbacks ==" sed -n '1,180p' packages/query-core/src/queryCache.ts echo "== Retryer resolve/fail dispatch behavior around completed status ==" sed -n '130,230p' packages/query-core/src/retryer.ts echo "== hydration.ts hydration path details ==" sed -n '200,330p' packages/query-core/src/hydration.tsRepository: TanStack/query
Length of output: 16383
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "== dispatch reducer complete sections ==" sed -n '530,710p' packages/query-core/src/query.ts echo echo "== hydration tests around rejected promises/dehydratedAt ==" rg -n -C 6 "promise|dehydratedAt|initialPromise|onError|onSettled|rejected" packages/query-core/src/__tests__/hydration.test.ts packages/query-core/src/__tests__/hydration.test.tsx packages/query-core/src/__tests__ 2>/dev/null | head -n 240 echo echo "== preact hydration tests around HydrationBoundary ==" rg -n -C 8 "HydrationBoundary|hydrationQueue|unobserved|dehydratedAt|promise|rejected" packages/preact-query/src packages/preact-query/src/__tests__ 2>/dev/null | head -n 260 echo echo "== query test helpers for dispatch/update ==" fd -i 'query.*test|hydration.test' packages/query-core/src/__tests__ -x sh -c 'echo "--- $1"; wc -l "$1"' sh {}Repository: TanStack/query
Length of output: 25709
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "== hydration.ts top and dispatch action ==" sed -n '1,120p' packages/query-core/src/hydration.ts echo rg -n -C 5 "type \?=|dispatch\(|query\.fetch|queryCache\.get|queryCache\.build|state:" packages/query-core/src/hydration.ts echo echo "== candidate hydration tests ==" sed -n '860,1045p' packages/query-core/src/__tests__/hydration.test.tsxRepository: TanStack/query
Length of output: 11231
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "== query.ts fetch action state definitions ==" rg -n -C 5 "fetchState|successState|QueryState|successState|errorUpdateCount" packages/query-core/src/query.ts | head -n 220Repository: TanStack/query
Length of output: 5988
Prevent duplicate hydration retryers for rejected dehydrated promises.
When HydrationBoundary feeds the same dehydrated query into both the layout hydration pass and the passive hydration pass, a rejected
initialPromisecan trigger two hydrate-side retry paths if the first path fails before the passive pass evaluates. Track query hashes hydrated during the layout pass and skip those hashes in the passive pass, or add equivalent deduplication inhydrate(). Add a regression test for an unobserved existing query with an already-rejected dehydrated promise.🤖 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/preact-query/src/HydrationBoundary.tsx` around lines 120 - 122, Prevent duplicate hydration retryers by deduplicating query hashes between the layout and passive hydration passes in HydrationBoundary, or equivalently within hydrate. Ensure an unobserved existing query with an already-rejected initialPromise is hydrated through only one retry path, and add a regression test covering this scenario.Source: MCP tools
✅ Addressed in commit 6ee0c1a
Fair, the passive pass was getting the whole queue including what the layout pass already handled. Fixed: the layout pass now keeps the queries it skipped in a ref and the passive one only hydrates those, so nothing goes through hydrate twice.
Easiest way to see the old behaviour was a deserializeData spy, it ran twice over the payload for an unobserved query and once now. There's a test for that.
@ostapondo, confirmed.deferredReflimits the passive pass to queries that the layout pass did not hydrate. ThedeserializeDataspy test verifies that an unobserved query is hydrated once.🐇 ✅
If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!
You are interacting with an AI system.Follow up on the reconciliation: I had it backwards, the two packages can't share the same shape.
I put the split in #11137 and it breaks the fix there. React cleans up a removed subtree's subscriptions in the passive phase, after the boundary's layout effect, so when a page unmounts and remounts in the same commit the outgoing observer is still on the query and the split skips it. Preact tears the old tree down while it diffs, so by the time the boundary commits the query really has no subscribers and the split works. Added a test for that case here, it passes.
So #11137 goes back to hydrating everything in the layout effect, which is safe there because React never commits a render it throws away, and this one keeps the split because Preact does commit a suspended tree. Two different behaviours out of two different commit models, not a choice.
Also caught while reviewing: nothing subscribes while
isRestoringis true, so a query on screen looks unsubscribed. That path now waits for the passive effect, with a test.ostapondo(GitHub profile, opens in a new tab)replied on
packages/preact-query/src/HydrationBoundary.tsxlines 120 to 122Fair, the passive pass was getting the whole queue including what the layout pass already handled. Fixed: the layout pass now keeps the queries it skipped in a ref and the passive one only hydrates those, so nothing goes through hydrate twice.
Easiest way to see the old behaviour was a deserializeData spy, it ran twice over the payload for an unobserved query and once now. There's a test for that.
coderabbitai[bot](GitHub profile, opens in a new tab)replied on
packages/preact-query/src/HydrationBoundary.tsxlines 120 to 122@ostapondo, confirmed.deferredReflimits the passive pass to queries that the layout pass did not hydrate. ThedeserializeDataspy test verifies that an unobserved query is hydrated once.🐇 ✅
If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!
You are interacting with an AI system.ostapondo(GitHub profile, opens in a new tab) linked this to fix #11155
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:
a39d2aee-001d-4541-a406-e8c55e4c221c📥 Commits
Reviewing files that changed from the base of the PR and between e6def1f3228087a0d74ff17a80776c9bd87c6fe9 and eebc2c1e39b8850440ec6fccdc95b2d39d0c76f9.
📒 Files selected for processing (2)
packages/preact-query/src/HydrationBoundary.tsxpackages/preact-query/src/__tests__/HydrationBoundary.test.tsx🚧 Files skipped from review as they are similar to previous changes (1)
📝 Walkthrough
Walkthrough#
HydrationBoundarynow hydrates unobserved queries during commit withuseLayoutEffect. Observed queries remain deferred to the passive effect. Tests cover suspended renders, remounts, observed queries, restoring mode, and duplicate deserialization.Changes#
Preact HydrationBoundary hydration
packages/preact-query/src/HydrationBoundary.tsxpackages/preact-query/src/__tests__/HydrationBoundary.test.tsx,.changeset/tidy-pugs-listen.mdEstimated code review effort: 3 (Moderate) | ~25 minutes
Sequence Diagram(s)#
Possibly related PRs
HydrationBoundaryto hydrate existing or unobserved queries during layout effects.🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
#11155.✨ 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