fix(query-core): fix combine not updating when queries change with stable reference #9954
main fromrefs/pull/9954/head·merged by TkDodo View on GitHub🎯 Changes#
Fixes #8781
Problem#
With stable combine, results lag one step behind when queries change.
This happens because getOptimisticResult runs before setQueries updates this.#result.
Solution#
Pass queryHashes to #combineResult to detect query changes before this.#result is updated.
✅ 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).
Summary by CodeRabbit#
Bug Fixes
- Combined query results now reliably update when the set of queries changes (add/remove/replace), ensuring aggregated results stay accurate.
Tests
- Added coverage for dynamic query counts and stable combine behavior to prevent regressions.
Chores
- Release patch entry added documenting the fix.
- 1
📝 Walkthrough
Walkthrough#
Adds tracking of query hashes in QueriesObserver to detect structural changes and force re-evaluation of a stable
combinefunction; updates optimistic result flow and tests to cover dynamic add/remove/replace scenarios and duplicate keys.Changes#
Cohort / File(s) Summary Changeset
\.changeset/swift-brooms-teach.md``New changeset added: patch bump for @tanstack/query-corewith description "fix stable combine reference not updating when queries change dynamically."Query Core Implementation
\packages/query-core/src/queriesObserver.ts``Adds private #lastQueryHashes?: string[]; threads query-hash computation throughgetOptimisticResultinto#combineResult(queryHashes?); compares and updates#lastQueryHashesto trigger recompute when hashes change. Method signature of#combineResultupdated.Query Core Tests
\packages/query-core/src/tests/queriesObserver.test.tsx``Adds tests exercising optimistic results and stable combinebehavior across adding, removing, replacing queries, duplicate keys, and early-return update scenarios.React Query Tests
\packages/react-query/src/tests/useQueries.test.tsx``Adds a test ensuring useQuerieswith a stablecombinereference returns correct results as the number of queries changes.Estimated code review effort#
🎯 4 (Complex) | ⏱️ ~45 minutes
Possibly related PRs#
- TanStack/query#9592 — Related changes ensuring memoized
combinere-runs when queries or their results change (per-index and overall change-detection overlap). - TanStack/query#9639 — Related refinements to queriesObserver change-detection and observer reconfiguration to avoid incorrect/infinite updates.
- TanStack/query#9886 — Additional modifications around queryHash handling and observer matching in QueriesObserver.
Suggested reviewers#
- TkDodo
Poem#
🐰 I tracked the hashes, one by one, So combines wake when queries run. Adding, swapping, left or right, The results now hop into sight. A cheeky fix — makes everything fun! 🥕✨
Pre-merge checks and finishing touches#
❌ Failed checks (1 warning)
Check name Status Explanation Resolution Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstringsto improve docstring coverage.✅ Passed checks (4 passed)
Check name Status Explanation Title check ✅ Passed The title accurately summarizes the main fix: ensuring the combine function updates when queries change with a stable reference. Description check ✅ Passed The description follows the template, explains the problem and solution clearly, and includes all required checklist items completed. Linked Issues check ✅ Passed The PR successfully addresses issue #8781 by detecting query changes via queryHashes before result updates, preventing the one-render lag with stable combine references. Out of Scope Changes check ✅ Passed All changes are scoped to fixing the stable combine reference bug: test additions, queryHashes tracking implementation, and changeset file. ✨ Finishing touches
- 📝 Generate docstrings
📜 Recent review details
Configuration used: defaults
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 89db791104f4435887de45f9eb4ffdd07da0bdb9 and 291afeca865cf86b6f415651e06a644fb9677c72.
📒 Files selected for processing (1)
packages/query-core/src/queriesObserver.ts
🧰 Additional context used
🧬 Code graph analysis (1)
packages/query-core/src/queriesObserver.ts (1)
packages/query-core/src/types.ts (1)
QueryObserverResult(903-908)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: Preview
- GitHub Check: Test
🔇 Additional comments (4)
packages/query-core/src/queriesObserver.ts (4)
46-46: LGTM!The new
#lastQueryHashesfield follows the naming convention of other caching fields (#lastCombine,#lastResult) and is appropriately typed as optional.
184-191: LGTM! Correctly captures query state before#resultis updated.Computing
queryHashesfrom the freshly matched observers and passing them to#combineResultensures that structural changes to the queries array are detected immediately during the optimistic result phase, beforesetQueriesupdatesthis.#result.
222-240: LGTM! The query hash comparison logic correctly detects structural changes.The implementation properly handles the key scenarios:
- First call:
#lastQueryHashesis undefined →queryHashesChangedis false, but#combinedResultis also undefined, so recomputation happens anyway. - Subsequent optimistic calls: Both hash arrays are defined, enabling detection of query additions/removals/replacements.
#notify()path: Called withoutqueryHashes, so#lastQueryHashesis preserved. This is correct since#notify()runs aftersetQuerieshas already updated#result, and thethis.#result !== this.#lastResultcheck handles that path.
295-309: Verify the intentional asymmetry between update paths.The
#notify()method calls#combineResultwithoutqueryHashes, which is correct because:- By the time
#notify()executes,setQuerieshas already updatedthis.#result - Changes are detected via
this.#result !== this.#lastResult
This intentional asymmetry preserves
#lastQueryHashesfor subsequent optimistic calls. Just confirming this design choice is understood for future maintainers.
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 and usage tips.- TanStack/query#9592 — Related changes ensuring memoized
github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: react-query
github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: query-core
View your CI Pipeline Execution ↗ for commit 4c928c0ac752a318d7b4c91dc4c18e34b6173324
Command Status Duration Result nx affected --targets=test:sherif,test:knip,tes...✅ Succeeded 56s View ↗
☁️ Nx Cloud last updated this comment at
2026-01-16 15:24:20UTCMore templates
- @tanstack/query-example-angular-auto-refetching
- @tanstack/query-example-angular-basic
- @tanstack/query-example-angular-basic-persister
- @tanstack/query-example-angular-devtools-panel
- @tanstack/query-example-angular-infinite-query-with-max-pages
- @tanstack/query-example-angular-optimistic-updates
- @tanstack/query-example-angular-pagination
- @tanstack/query-example-angular-query-options-from-a-service
- @tanstack/query-example-angular-router
- @tanstack/query-example-angular-rxjs
- @tanstack/query-example-angular-simple
- @tanstack/query-example-solid-astro
- @tanstack/query-example-solid-basic
- @tanstack/query-example-solid-basic-graphql-request
- @tanstack/query-example-solid-default-query-function
- @tanstack/query-example-solid-simple
- @tanstack/query-example-solid-start-streaming
- @tanstack/query-example-vue-2.6-basic
- @tanstack/query-example-vue-2.7-basic
- @tanstack/query-example-vue-basic
- @tanstack/query-example-vue-dependent-queries
- @tanstack/query-example-vue-nuxt3
- @tanstack/query-example-vue-persister
- @tanstack/query-example-vue-simple
- @tanstack/query-example-svelte-auto-refetching
- @tanstack/query-example-svelte-basic
- @tanstack/query-example-svelte-load-more-infinite-scroll
- @tanstack/query-example-svelte-optimistic-updates
- @tanstack/query-example-svelte-playground
- @tanstack/query-example-svelte-simple
- @tanstack/query-example-svelte-ssr
- @tanstack/query-example-svelte-star-wars
- @tanstack/query-example-react-algolia
- @tanstack/query-example-react-auto-refetching
- @tanstack/query-example-react-basic
- @tanstack/query-example-react-basic-graphql-request
- @tanstack/query-example-chat
- @tanstack/query-example-react-default-query-function
- @tanstack/query-example-react-devtools-panel
- @tanstack/query-example-eslint-legacy
- @tanstack/query-example-react-infinite-query-with-max-pages
- @tanstack/query-example-react-load-more-infinite-scroll
- @tanstack/query-example-react-nextjs
- @tanstack/query-example-react-nextjs-app-prefetching
- @tanstack/query-example-nextjs-suspense-streaming
- @tanstack/query-example-react-offline
- @tanstack/query-example-react-optimistic-updates-cache
- @tanstack/query-example-react-optimistic-updates-ui
- @tanstack/query-example-react-pagination
- @tanstack/query-example-react-playground
- @tanstack/query-example-react-prefetching
- @tanstack/query-example-react-react-native
- @tanstack/query-example-react-router
- @tanstack/query-example-react-rick-morty
- @tanstack/query-example-react-shadow-dom
- @tanstack/query-example-react-simple
- @tanstack/query-example-react-star-wars
- @tanstack/query-example-react-suspense
@tanstack/angular-query-experimental
npm i https://pkg.pr.new/@tanstack/angular-query-experimental@9954@tanstack/eslint-plugin-query
npm i https://pkg.pr.new/@tanstack/eslint-plugin-query@9954@tanstack/query-async-storage-persister
npm i https://pkg.pr.new/@tanstack/query-async-storage-persister@9954@tanstack/query-broadcast-client-experimental
npm i https://pkg.pr.new/@tanstack/query-broadcast-client-experimental@9954@tanstack/query-core
npm i https://pkg.pr.new/@tanstack/query-core@9954@tanstack/query-devtools
npm i https://pkg.pr.new/@tanstack/query-devtools@9954@tanstack/query-persist-client-core
npm i https://pkg.pr.new/@tanstack/query-persist-client-core@9954@tanstack/query-sync-storage-persister
npm i https://pkg.pr.new/@tanstack/query-sync-storage-persister@9954@tanstack/react-query
npm i https://pkg.pr.new/@tanstack/react-query@9954@tanstack/react-query-devtools
npm i https://pkg.pr.new/@tanstack/react-query-devtools@9954@tanstack/react-query-next-experimental
npm i https://pkg.pr.new/@tanstack/react-query-next-experimental@9954@tanstack/react-query-persist-client
npm i https://pkg.pr.new/@tanstack/react-query-persist-client@9954@tanstack/solid-query
npm i https://pkg.pr.new/@tanstack/solid-query@9954@tanstack/solid-query-devtools
npm i https://pkg.pr.new/@tanstack/solid-query-devtools@9954@tanstack/solid-query-persist-client
npm i https://pkg.pr.new/@tanstack/solid-query-persist-client@9954@tanstack/svelte-query
npm i https://pkg.pr.new/@tanstack/svelte-query@9954@tanstack/svelte-query-devtools
npm i https://pkg.pr.new/@tanstack/svelte-query-devtools@9954@tanstack/svelte-query-persist-client
npm i https://pkg.pr.new/@tanstack/svelte-query-persist-client@9954@tanstack/vue-query
npm i https://pkg.pr.new/@tanstack/vue-query@9954@tanstack/vue-query-devtools
npm i https://pkg.pr.new/@tanstack/vue-query-devtools@9954commit:
4c928c0Codecov Report#
:white_check_mark: All modified and coverable lines are covered by tests. :white_check_mark: Project coverage is 59.84%. Comparing base (
0d07172) to head (4c928c0). :warning: Report is 1 commits behind head on main.Additional details and impacted files
@@ Coverage Diff @@ ## main #9954 +/- ## =========================================== + Coverage 45.83% 59.84% +14.01% =========================================== Files 200 129 -71 Lines 8524 5748 -2776 Branches 1978 1590 -388 =========================================== - Hits 3907 3440 -467 + Misses 4157 1993 -2164 + Partials 460 315 -145- :snowflake: Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
- :package: JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
TkDodo approved these changes
TkDodo merged this53fc74e
TkDodo closed this
Sign in to join this conversation.
🦋 Changeset detected#
Latest commit: 4c928c0ac752a318d7b4c91dc4c18e34b6173324
The changes in this PR will be included in the next version bump.
This PR includes changesets to release 19 packages
Not sure what this means? Click here to learn what changesets are.
Click here if you're a maintainer who wants to add another changeset to this PR