fix(react-db): idiomatic `useLiveQuery` & `useLiveSuspenseQuery` hooks #1721
main fromrefs/pull/1721/head·opened 🎯 Changes#
These hooks where using refs to track previous versions of certain variables, and reading those during render, which is an anti-pattern that breaks the Rules of Hooks and may lead to subtle bugs, especially in concurrent mode.
Using state instead is more idiomatic and ensures there will be no state tearing, even during concurrent mode updates.
I discovered this while trying to work around an issue where an error thrown by the queryFn in QueryCollection would lead to infinite retries, and eventually, the browser running out of memory.
TODO: I haven't yet checked or adjusted the following hooks:
useLiveInfiniteQueryuseLiveQueryEffectusePacedMutations
✅ Checklist#
- I have tested this code locally with
pnpm test. There are failing tests, but they were not introduced by my changes.
🚀 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
- Improved live query state handling for more reliable updates during concurrent rendering.
- Fixed collection changes and Suspense readiness transitions to update consistently.
- Improved promise reuse during Suspense preloading.
- Stabilized live query subscriptions and returned results to reduce unnecessary updates.
- Improved consistency when live query inputs change, helping prevent stale or mismatched results.
- 1
Actionable comments posted: 2
🤖 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-db/src/useLiveQuery.ts`: - Around line 335-340: The needsNewCollection condition should not use !collection as its initialization check, because disabled queries may intentionally leave collection null and repeatedly update state. In the relevant useLiveQuery logic, use prevDeps === null for initialization while preserving the existing config and dependency-change checks. In `@packages/react-db/src/useLiveSuspenseQuery.ts`: - Around line 190-193: Guard the ready-state update in the useLiveSuspenseQuery flow by calling setHasBeenReady(true) only when collectionStatus is ready and hasBeenReady is false, preventing repeated render-phase state updates while preserving the existing ready-state behavior.🪄 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:
8779cc43-0926-4a80-a890-cde7642f1fab📥 Commits
Reviewing files that changed from the base of the PR and between dc53f0ecbc38e173af68d829ff2de97531494722 and 5f23973b183ec7a6876a466ce346beef53c13645.
📒 Files selected for processing (3)
.changeset/eleven-gifts-shine.mdpackages/react-db/src/useLiveQuery.tspackages/react-db/src/useLiveSuspenseQuery.ts
@@ -335,9 +325,16 @@325+ object,326+ string | number,327+ {}328+ > | null>(null)329+ const [prevCollection, setPrevCollection] = useState(collection)330+ const [prevDeps, setPrevDeps] = useState<Array<unknown> | null>(null)331+ const [prevConfig, setPrevConfig] = useState<unknown>(null)335332336333 // Check if we need to create/recreate the collection337334 const needsNewCollection =338- !collectionRef.current ||339- (inputIsCollection && configRef.current !== configOrQueryOrCollection) ||335+ !collection ||336+ (inputIsCollection && prevConfig !== configOrQueryOrCollection) ||340337 (!inputIsCollection &&341- (depsRef.current === null ||342- depsRef.current.length !== deps.length ||343- depsRef.current.some((dep, i) => dep !== deps[i])))338+ (prevDeps === null ||339+ prevDeps.length !== deps.length ||340+ prevDeps.some((dep, i) => dep !== deps[i])))🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash set -euo pipefail # Locate existing disabled-query coverage for this hook. fd -t f . packages/react-db | rg '\.(test|spec)\.(ts|tsx)$' | while IFS= read -r file; do rg -n -C 3 'useLiveQuery|isEnabled|undefined|null|disabled' "$file" || true doneRepository: TanStack/db
Length of output: 31370
🏁 Script executed:
#!/bin/bash set -euo pipefail printf '%s\n' '--- hook implementation ---' sed -n '300,430p' packages/react-db/src/useLiveQuery.ts printf '%s\n' '--- relevant disabled-query tests ---' sed -n '1970,2135p' packages/react-db/tests/useLiveQuery.test.ts 2>/dev/null || true sed -n '2288,2360p' packages/react-db/tests/useLiveQuery.test.ts 2>/dev/null || true printf '%s\n' '--- candidate test files ---' fd -t f . packages/react-db | rg 'useLiveQuery.*\.(test|spec)\.(ts|tsx)$|useLiveQuery\.(test|spec)\.(ts|tsx)$' || trueRepository: TanStack/db
Length of output: 5979
Prevent a render loop for disabled queries.
When the callback returns
nullorundefined,collectionremainsnull, soneedsNewCollectionstays true.setPrevDeps([...deps])then creates a new array during every render and triggers React's too-many-renders error.Use
prevDeps === nullas the initialization check instead of!collection.🤖 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-db/src/useLiveQuery.ts` around lines 335 - 340, The needsNewCollection condition should not use !collection as its initialization check, because disabled queries may intentionally leave collection null and repeatedly update state. In the relevant useLiveQuery logic, use prevDeps === null for initialization while preserving the existing config and dependency-change checks.✅ Addressed in commit 66ed096
@@ -189,6 +189,5 @@189189190190 // Track when we reach ready state191191 if (collectionStatus === `ready`) {192- hasBeenReadyRef.current = true193- promiseRef.current = null192+ setHasBeenReady(true)194193 }🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash set -euo pipefail # Locate Suspense hook tests that can cover a collection reaching ready status. fd -t f . packages/react-db | rg '\.(test|spec)\.(ts|tsx)$' | while IFS= read -r file; do rg -n -C 3 'useLiveSuspenseQuery|status.*ready|Too many re-renders' "$file" || true doneRepository: TanStack/db
Length of output: 5411
🏁 Script executed:
#!/bin/bash set -euo pipefail echo '--- hook outline ---' ast-grep outline packages/react-db/src/useLiveSuspenseQuery.ts --view expanded echo '--- hook lines 130-235 ---' cat -n packages/react-db/src/useLiveSuspenseQuery.ts | sed -n '130,235p' echo '--- suspense test outline ---' ast-grep outline packages/react-db/tests/useLiveSuspenseQuery.test.tsx --view expanded echo '--- suspense tests around rerender/readiness ---' cat -n packages/react-db/tests/useLiveSuspenseQuery.test.tsx | sed -n '1,250p' cat -n packages/react-db/tests/useLiveSuspenseQuery.test.tsx | sed -n '560,705p' echo '--- React dependency declarations ---' rg -n -C 2 '"react"|"react-dom"|reactVersion|React' package.json packages/*/package.json pnpm-lock.yaml yarn.lock package-lock.json 2>/dev/null | head -200 || true echo '--- available local React modules ---' node -e "for (const name of ['react','react-dom','react-test-renderer']) { try { console.log(name, require.resolve(name)) } catch { console.log(name, 'not available') } }"Repository: TanStack/db
Length of output: 20083
🌐 Web query:
React 19.2.4 source render phase state update same value enqueueRenderPhaseUpdate too many re-renders💡 Result:
In React, triggering a state update directly within the component's main render body is an anti-pattern that can lead to an "infinite loop" error [1][2]. Specifically, when you call a state setter function during the render phase, React invokes
enqueueRenderPhaseUpdate[1][3][4]. This function marks the component as needing a re-render by setting a internal flag (didScheduleRenderPhaseUpdateDuringThisPasstotrue), which forces React to restart the render pass for that component [2]. If this process repeats continuously—such as calling the state setter every time the component function executes—React reaches a built-in safety limit (controlled by theRE_RENDER_LIMITconstant) and throws the "Too many re-renders" error to prevent an infinite loop [2]. Regarding the behavior of setting state to the same value (e.g.,setState(sameValue)): 1. Normal Updates (Event Handlers/Effects): If you update state to the same value outside the render phase (e.g., in anonClickhandler oruseEffect), React can often "eagerly" bail out of a re-render [1][5][6]. It compares the new value with the current state; if they are identical, it skips scheduling the re-render entirely [5][6]. 2. Render Phase Updates: Even if you set state to the same value during the render phase, the component function has already been invoked, and theenqueueRenderPhaseUpdatemechanism is triggered [2]. Because this occurs while the component is already rendering, it forces a re-render pass [2]. While React attempts to bail out of unnecessary work, the mere act of triggering the state update during rendering is what initiates the loop, leading to the "Too many re-renders" error if the condition for that state update remains true on subsequent passes [1][2]. To resolve this, ensure that any logic resulting in state updates is moved out of the component's direct execution body and placed inside appropriate hooks likeuseEffector inside event handlers [1][7]. If you must perform logic during rendering, consider usinguseMemoto compute derived values rather than storing them in state [8].Citations:
- 1: https://j1032w.github.io/blog/how-useState-hook-works-internally-in-react-18
- 2: https://exchangetuts.com/index.php/why-react-goes-infinite-when-i-set-state-in-function-body-1768671903541396
- 3: https://jser.dev/2023-06-19-how-does-usestate-work/
- 4: https://levelup.gitconnected.com/behind-the-scenes-of-usestate-implementation-insights-fd7e28707e10
- 5: https://luxing.dev/blog/react
- 6: https://gist.github.com/pshaddel/d69ab19491a69ca3d860d3903b946ce0
- 7: https://react.dev/learn/queueing-a-series-of-state-updates
- 8: https://react.wiki/performance/initial-vs-rerender/
🏁 Script executed:
#!/bin/bash set -euo pipefail url='https://raw.githubusercontent.com/facebook/react/v19.2.4/packages/react-reconciler/src/ReactFiberHooks.js' tmp=$(mktemp) trap 'rm -f "$tmp"' EXIT curl -fsSL "$url" -o "$tmp" echo '--- render-phase dispatch ---' rg -n -C 12 'isRenderPhaseUpdate|enqueueRenderPhaseUpdate|dispatchSetStateInternal' "$tmp" | head -220 echo '--- rerender loop ---' rg -n -C 16 'RE_RENDER_LIMIT|didScheduleRenderPhaseUpdateDuringThisPass|renderWithHooksAgain' "$tmp" | head -220Repository: TanStack/db
Length of output: 16382
Guard the ready-state update.
At
packages/react-db/src/useLiveSuspenseQuery.ts:192,setHasBeenReady(true)runs during everyreadyrender. React retries render-phase updates until they stop, then throwsToo many re-renders.Update the state only when
hasBeenReadyis false.Proposed fix
- if (collectionStatus === `ready`) { + if (collectionStatus === `ready` && !hasBeenReady) { setHasBeenReady(true) }📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
// Track when we reach ready state if (collectionStatus === `ready` && !hasBeenReady) { setHasBeenReady(true) }🤖 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-db/src/useLiveSuspenseQuery.ts` around lines 190 - 193, Guard the ready-state update in the useLiveSuspenseQuery flow by calling setHasBeenReady(true) only when collectionStatus is ready and hasBeenReady is false, preventing repeated render-phase state updates while preserving the existing ready-state behavior.✅ Addressed in commit 5582d36
Closing this stale implementation because it predates the current DbClient, query identity, SSR hydration, deferred-source, and external-store architecture. The general render-purity concern can remain a design topic, but any implementation now needs a current-main reproduction and the modern server-snapshot and lifecycle contracts.
KyleAMathews(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.
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:
65dc9dad-a4ac-4d82-9a71-856789ad8974📥 Commits
Reviewing files that changed from the base of the PR and between 5582d36cb57ed21a6ce750e042c031f5a4f5ab7a and 66ed096461c23ca54c8dc65825fde7db5c79b91f.
📒 Files selected for processing (1)
packages/react-db/src/useLiveQuery.ts🚧 Files skipped from review as they are similar to previous changes (1)
📝 Walkthrough
Walkthrough#
useLiveQueryanduseLiveSuspenseQueryreplace ref-based tracking with React state. The hooks update collection handling, observer subscriptions, Suspense promise caching, readiness tracking, and result memoization.Changes#
React live-query hooks
packages/react-db/src/useLiveQuery.ts,.changeset/eleven-gifts-shine.mduseLiveQuerystores collection, dependency, and configuration values in state. It recreates observers when collections change and uses memoized callbacks withuseSyncExternalStore. The changeset documents the patch.packages/react-db/src/useLiveSuspenseQuery.tsuseLiveSuspenseQuerystores collection and readiness in state, caches rejection-safe preload promises in aWeakMap, and memoizes the returned result.Estimated code review effort: 3 (Moderate) | ~20 minutes
Mergeability Score: ⚪ Minimal · up to
66ed0The PR replaces ref-based version tracking with state in two published React hooks and includes a changeset. No actionable merge-blocking risk remains; it is merge-ready after normal checks and review.
Possibly related PRs
useLiveQuery.ts.useLiveQueryanduseLiveSuspenseQueryimplementations.🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
✨ 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