Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

useLiveQuery.ts

1,064 lines34.1 KB

1'use client'
2​
3import { useRef, useSyncExternalStore } from 'react'
4import {
5 UnhashableQueryIRError,
6 createLiveQueryObserver,
7 deepEquals,
8 getPreparedLiveQueryIdentity,
9 getStableValueHash,
10 isCollection,
11 prepareLiveQueryValue,
12 resolveLiveQueryValue,
13} from '@tanstack/db'
14import { useOptionalDbClient } from './DbProvider'
15import { setLiveQueryResultInfo } from './live-query-internals'
16import { shouldWarnInDevelopment } from './development'
17import {
18 claimSourceIds,
19 createSourceIdBindings,
20 getPreparedSources,
21 getSourceObjectToken,
22 resumeSyncStarts,
23} from './source-id-bindings'
24import type {
25 Collection,
26 CollectionImpl,
27 CollectionStatus,
28 Context,
29 DbClient,
30 GetResult,
31 InferResultType,
32 InitialQueryBuilder,
33 LiveQueryCollectionConfig,
34 LiveQueryObserver,
35 LiveQueryPersistedStatus,
36 NonSingleResult,
37 QueryBuilder,
38 SingleResult,
39} from '@tanstack/db'
40​
41const DEFAULT_GC_TIME_MS = 1 // Live queries created by useLiveQuery are cleaned up immediately (0 disables GC)
42// Suspense renders can be abandoned before React subscribes. Keep their
43// collection briefly so a nearby retry can commit without starting over.
44const DEFAULT_SUSPENSE_GC_TIME_MS = 5000
45const DERIVED_IDENTITY_SINGLE_RENDER_WARN_MS = 16
46const DERIVED_IDENTITY_RENDER_COUNT_WARN_THRESHOLD = 10
47const DERIVED_IDENTITY_TOTAL_WARN_MS = 50
48const warnedDepsCallsites = new Set<string>()
49const warnedDerivedIdentityCallsites = new Set<string>()
50const warnedUnhashableIdentityCallsites = new Set<string>()
51const unpreparedQueryValue = Symbol(`unpreparedQueryValue`)
52​
53type SuspenseCollection = Collection<object, string | number, {}>
54type SuspenseCollectionEntry = {
55 collection: SuspenseCollection
56 removeStatusListeners: () => void
58​
59const unscopedSuspenseCollections = new Map<string, SuspenseCollectionEntry>()
60const suspenseCollectionsByClient = new WeakMap<
61 DbClient,
62 Map<string, SuspenseCollectionEntry>
63>()
64function getSourceQualifiedSuspenseKey(
65 preparedValue: unknown,
66 queryHash: string,
67 client: DbClient | undefined,
68): string {
69 const sourceIds = getPreparedSources(
70 preparedValue,
71 client,
72 `useLiveSuspenseQuery`,
73 ).map(getSourceObjectToken)
74 if (sourceIds.length === 0) return queryHash
75 return `${sourceIds.join(`,`)}:${queryHash}`
77​
78function getSuspenseCollections(
79 client: DbClient | undefined,
80): Map<string, SuspenseCollectionEntry> {
81 if (!client) return unscopedSuspenseCollections
82 let collections = suspenseCollectionsByClient.get(client)
83 if (!collections) {
84 collections = new Map()
85 suspenseCollectionsByClient.set(client, collections)
86 }
87 return collections
89​
90function releaseSuspenseCollection(
91 collections: Map<string, SuspenseCollectionEntry>,
92 queryHash: string,
93 collection: SuspenseCollection,
94): void {
95 const entry = collections.get(queryHash)
96 if (entry?.collection !== collection) return
97 collections.delete(queryHash)
98 entry.removeStatusListeners()
100​
101export type DerivedIdentityProfiler = {
102 renderCount: number
103 totalMs: number
104 maxMs: number
105 warned: boolean
107​
108export type UseLiveQueryStatus = CollectionStatus | `disabled`
109export type LiveQueryKey = ReadonlyArray<unknown>
110type UseLiveQueryConfigOptions<TContext extends Context> = Omit<
111 LiveQueryCollectionConfig<TContext>,
112 `query`
113> & {
114 /**
115 * Explicit identity for queries that contain opaque functional variants or
116 * are hot enough that deriving identity from structured IR is too expensive.
117 * Structured queries should omit this so DB can derive identity directly.
118 */
119 queryKey?: LiveQueryKey
120 /** Override the nearest DbProvider for this query. */
121 client?: DbClient
123​
124type ConfiguredQueryBuilder<TContext extends Context> = Extract<
125 LiveQueryCollectionConfig<TContext>[`query`],
126 QueryBuilder<TContext>
128​
129export type UseLiveQueryConfig<TContext extends Context> =
130 UseLiveQueryConfigOptions<TContext> &
131 Pick<LiveQueryCollectionConfig<TContext>, `query`>
132​
133export type ConditionalUseLiveQueryConfig<TContext extends Context> =
134 UseLiveQueryConfigOptions<TContext> & {
135 query:
136 | ConfiguredQueryBuilder<TContext>
137 | ((
138 q: InitialQueryBuilder,
139 ) => ConfiguredQueryBuilder<TContext> | undefined | null)
140 }
141​
142export function warnDeprecatedDepsArray(
143 hookName: `useLiveQuery` | `useLiveInfiniteQuery` = `useLiveQuery`,
144): void {
145 if (!(
146 shouldWarnInDevelopment(`TANSTACK_DB_DISABLE_DEPRECATION_WARNINGS`) &&
147 process.env.NODE_ENV !== `production`
148 )) {
149 return
150 }
151​
152 const callsite = getWarningCallsite(4)
153 if (warnedDepsCallsites.has(callsite)) {
154 return
155 }
156 warnedDepsCallsites.add(callsite)
157 const replacement =
158 hookName === `useLiveQuery`
159 ? `useLiveQuery({ query })`
160 : `useLiveInfiniteQuery(query, { queryKey })`
161 console.warn(
162 `[${hookName}] The dependency-array form is deprecated and will be removed in 1.0. Use ${replacement} instead. Provide queryKey only for functional/opaque queries or to avoid deriving identity from structured query IR on render.`,
163 )
165​
166function getCurrentTime(): number {
167 return typeof performance !== `undefined` &&
168 typeof performance.now === `function`
169 ? performance.now()
170 : Date.now()
172​
173function getWarningCallsite(stackIndex: number): string {
174 const stack = new Error().stack ?? `unknown`
175 const lines = stack.split(`\n`)
176 const userFrame = lines
177 .slice(1)
178 .find(
179 (line) =>
180 !line.includes(`useLiveQuery.ts`) &&
181 !line.includes(`useLiveSuspenseQuery.ts`) &&
182 !line.includes(`useLiveInfiniteQuery.ts`),
183 )
184 return userFrame?.trim() ?? lines[stackIndex]?.trim() ?? stack
186​
187function warnDerivedIdentityHotPath(
188 profiler: DerivedIdentityProfiler,
189 durationMs: number,
190): void {
191 if (
192 profiler.warned ||
193 !(
194 shouldWarnInDevelopment(`TANSTACK_DB_DISABLE_QUERY_IDENTITY_WARNINGS`) &&
195 process.env.NODE_ENV !== `production`
196 )
197 ) {
198 return
199 }
200​
201 const isSlowSingleRender =
202 durationMs >= DERIVED_IDENTITY_SINGLE_RENDER_WARN_MS
203 const isHotRenderPath =
204 profiler.renderCount >= DERIVED_IDENTITY_RENDER_COUNT_WARN_THRESHOLD &&
205 profiler.totalMs >= DERIVED_IDENTITY_TOTAL_WARN_MS
206​
207 if (!isSlowSingleRender && !isHotRenderPath) {
208 return
209 }
210​
211 const callsite = getWarningCallsite(5)
212 if (warnedDerivedIdentityCallsites.has(callsite)) {
213 profiler.warned = true
214 return
215 }
216​
217 warnedDerivedIdentityCallsites.add(callsite)
218 profiler.warned = true
219​
220 const reason = isSlowSingleRender
221 ? `one render took ${durationMs.toFixed(1)}ms`
222 : `${profiler.renderCount} renders took ${profiler.totalMs.toFixed(1)}ms`
223​
224 console.warn(
225 `[useLiveQuery] Deriving live query identity from structured query IR is running on a hot render path (${reason}, max ${profiler.maxMs.toFixed(1)}ms). ` +
226 `Provide an explicit queryKey to skip rebuilding and hashing the IR on every render: useLiveQuery({ queryKey: [...], query }).`,
227 )
229​
230function getExplicitQueryKey(value: unknown): LiveQueryKey | undefined {
231 return value &&
232 typeof value === `object` &&
233 Array.isArray((value as { queryKey?: unknown }).queryKey)
234 ? (value as { queryKey: LiveQueryKey }).queryKey
235 : undefined
237​
238function getExplicitDbClient(value: unknown): DbClient | undefined {
239 return value &&
240 typeof value === `object` &&
241 `client` in value &&
242 (value as { client?: unknown }).client !== undefined
243 ? (value as { client: DbClient }).client
244 : undefined
246​
247export function prepareQueryValue(
248 value: unknown,
249 dbClient: DbClient | undefined,
250 deferredCollections: Set<CollectionImpl<any, string | number, any, any, any>>,
251): unknown {
252 return prepareLiveQueryValue(value, dbClient, deferredCollections)
254​
255type DerivedQueryPreparation =
256 | {
257 status: `hashable`
258 value: unknown
259 identityDeps: Array<unknown>
260 }
261 | {
262 status: `unhashable`
263 value: unknown
264 error: UnhashableQueryIRError
265 }
266​
267export function prepareDerivedQuery(
268 value: unknown,
269 dbClient: DbClient | undefined,
270 profiler: DerivedIdentityProfiler,
271 deferredCollections: Set<CollectionImpl<any, string | number, any, any, any>>,
272): DerivedQueryPreparation {
273 const shouldProfile =
274 shouldWarnInDevelopment(`TANSTACK_DB_DISABLE_QUERY_IDENTITY_WARNINGS`) &&
275 process.env.NODE_ENV !== `production`
276 const start = shouldProfile ? getCurrentTime() : 0
277 const preparedValue = prepareQueryValue(value, dbClient, deferredCollections)
278​
279 try {
280 const identity = getPreparedLiveQueryIdentity(preparedValue)
281 return {
282 status: `hashable`,
283 value: preparedValue,
284 identityDeps: [`derived`, identity],
285 }
286 } catch (error) {
287 if (error instanceof UnhashableQueryIRError) {
288 return { status: `unhashable`, value: preparedValue, error }
289 }
290​
291 throw error
292 } finally {
293 if (shouldProfile) {
294 const durationMs = getCurrentTime() - start
295 profiler.renderCount += 1
296 profiler.totalMs += durationMs
297 profiler.maxMs = Math.max(profiler.maxMs, durationMs)
298 warnDerivedIdentityHotPath(profiler, durationMs)
299 }
300 }
302​
303export function warnUnhashableDerivedIdentity(
304 error: UnhashableQueryIRError,
305): void {
306 if (!(
307 shouldWarnInDevelopment(`TANSTACK_DB_DISABLE_QUERY_IDENTITY_WARNINGS`) &&
308 process.env.NODE_ENV !== `production`
309 )) {
310 return
311 }
312​
313 const callsite = getWarningCallsite(4)
314 if (warnedUnhashableIdentityCallsites.has(callsite)) {
315 return
316 }
317 warnedUnhashableIdentityCallsites.add(callsite)
318​
319 console.warn(
320 `[useLiveQuery] This query cannot derive a stable identity because ${error.reason} at ${error.path}. ` +
321 `It will keep the legacy mount-stable behavior for now. Add queryKey: [...] to make captured values reactive. ` +
322 `Unhashable queries without queryKey will throw in 1.0.`,
323 )
325​
326/**
327 * Create a live query using a query function.
328 * @param queryFn - Query function that defines what data to fetch
329 * @param deps - Deprecated array of dependencies that trigger query re-execution when changed
330 * @returns Object with reactive data, state, and status information
331 * @example
332 * // Prefer config object syntax
333 * const { data, isLoading } = useLiveQuery({
334 * query: (q) =>
335 * q.from({ todos: todosCollection })
336 * .where(({ todos }) => eq(todos.completed, false))
337 * .select(({ todos }) => ({ id: todos.id, text: todos.text }))
338 * })
339 *
340 * @example
341 * // Single result query
342 * const { data } = useLiveQuery({
343 * query: (q) => q.from({ todos: todosCollection })
344 * .where(({ todos }) => eq(todos.id, 1))
345 * .findOne()
346 * })
347 *
348 * @example
349 * // Structured captured values are included in derived query identity
350 * const { data, state } = useLiveQuery({
351 * query: (q) => q.from({ todos: todosCollection })
352 * .where(({ todos }) => gt(todos.priority, minPriority)),
353 * })
354 *
355 * @example
356 * // Return undefined or null to disable a query
357 * const { data, isEnabled } = useLiveQuery({
358 * query: (q) => {
359 * if (!userId) return undefined
360 * return q.from({ todos: todosCollection })
361 * .where(({ todos }) => eq(todos.userId, userId))
362 * },
363 * })
364 *
365 * @example
366 * // Join pattern
367 * const { data } = useLiveQuery({
368 * query: (q) =>
369 * q.from({ issues: issueCollection })
370 * .join({ persons: personCollection }, ({ issues, persons }) =>
371 * eq(issues.userId, persons.id)
372 * )
373 * .select(({ issues, persons }) => ({
374 * id: issues.id,
375 * title: issues.title,
376 * userName: persons.name
377 * }))
378 * })
379 *
380 * @example
381 * // Handle loading and error states
382 * const { data, isLoading, isError, status } = useLiveQuery({
383 * query: (q) => q.from({ todos: todoCollection })
384 * })
385 *
386 * if (isLoading) return <div>Loading...</div>
387 * if (isError) return <div>Error: {status}</div>
388 *
389 * return (
390 * <ul>
391 * {data.map(todo => <li key={todo.id}>{todo.text}</li>)}
392 * </ul>
393 * )
394 */
395// Overload 1: Accept query function that always returns QueryBuilder
396export function useLiveQuery<TContext extends Context>(
397 queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>,
398 deps?: Array<unknown>,
399): {
400 state: Map<string | number, GetResult<TContext>>
401 data: InferResultType<TContext>
402 collection: Collection<GetResult<TContext>, string | number, {}>
403 status: CollectionStatus // Can't be disabled if always returns QueryBuilder
404 isLoading: boolean
405 isReady: boolean
406 persistedStatus: LiveQueryPersistedStatus
407 isPersistedReady: boolean
408 persistedError: unknown | undefined
409 isIdle: boolean
410 isError: boolean
411 isCleanedUp: boolean
412 isEnabled: true // Always true if always returns QueryBuilder
414​
415// Overload 2: Accept query function that can return undefined/null
416export function useLiveQuery<TContext extends Context>(
417 queryFn: (
418 q: InitialQueryBuilder,
419 ) => QueryBuilder<TContext> | undefined | null,
420 deps?: Array<unknown>,
421): {
422 state: Map<string | number, GetResult<TContext>> | undefined
423 data: InferResultType<TContext> | undefined
424 collection: Collection<GetResult<TContext>, string | number, {}> | undefined
425 status: UseLiveQueryStatus
426 isLoading: boolean
427 isReady: boolean
428 persistedStatus: LiveQueryPersistedStatus
429 isPersistedReady: boolean
430 persistedError: unknown | undefined
431 isIdle: boolean
432 isError: boolean
433 isCleanedUp: boolean
434 isEnabled: boolean
436​
437// Overload 3: Accept query function that can return LiveQueryCollectionConfig
438export function useLiveQuery<TContext extends Context>(
439 queryFn: (
440 q: InitialQueryBuilder,
441 ) => LiveQueryCollectionConfig<TContext> | undefined | null,
442 deps?: Array<unknown>,
443): {
444 state: Map<string | number, GetResult<TContext>> | undefined
445 data: InferResultType<TContext> | undefined
446 collection: Collection<GetResult<TContext>, string | number, {}> | undefined
447 status: UseLiveQueryStatus
448 isLoading: boolean
449 isReady: boolean
450 persistedStatus: LiveQueryPersistedStatus
451 isPersistedReady: boolean
452 persistedError: unknown | undefined
453 isIdle: boolean
454 isError: boolean
455 isCleanedUp: boolean
456 isEnabled: boolean
458​
459// Overload 4: Accept query function that can return Collection
460export function useLiveQuery<
461 TResult extends object,
462 TKey extends string | number,
463 TUtils extends Record<string, any>,
464>(
465 queryFn: (
466 q: InitialQueryBuilder,
467 ) => Collection<TResult, TKey, TUtils> | undefined | null,
468 deps?: Array<unknown>,
469): {
470 state: Map<TKey, TResult> | undefined
471 data: Array<TResult> | undefined
472 collection: Collection<TResult, TKey, TUtils> | undefined
473 status: UseLiveQueryStatus
474 isLoading: boolean
475 isReady: boolean
476 persistedStatus: LiveQueryPersistedStatus
477 isPersistedReady: boolean
478 persistedError: unknown | undefined
479 isIdle: boolean
480 isError: boolean
481 isCleanedUp: boolean
482 isEnabled: boolean
484​
485// Overload 5: Accept query function that can return all types
486export function useLiveQuery<
487 TContext extends Context,
488 TResult extends object,
489 TKey extends string | number,
490 TUtils extends Record<string, any>,
491>(
492 queryFn: (
493 q: InitialQueryBuilder,
494 ) =>
495 | QueryBuilder<TContext>
496 | LiveQueryCollectionConfig<TContext>
497 | Collection<TResult, TKey, TUtils>
498 | undefined
499 | null,
500 deps?: Array<unknown>,
501): {
502 state:
503 Map<string | number, GetResult<TContext>> | Map<TKey, TResult> | undefined
504 data: InferResultType<TContext> | Array<TResult> | undefined
505 collection:
506 | Collection<GetResult<TContext>, string | number, {}>
507 | Collection<TResult, TKey, TUtils>
508 | undefined
509 status: UseLiveQueryStatus
510 isLoading: boolean
511 isReady: boolean
512 persistedStatus: LiveQueryPersistedStatus
513 isPersistedReady: boolean
514 persistedError: unknown | undefined
515 isIdle: boolean
516 isError: boolean
517 isCleanedUp: boolean
518 isEnabled: boolean
520​
521/**
522 * Create a live query using configuration object
523 * @param config - Configuration object with query and options
524 * @param deps - Deprecated array of dependencies that trigger query re-execution when changed
525 * @returns Object with reactive data, state, and status information
526 * @example
527 * // Basic config object usage
528 * const { data, status } = useLiveQuery({
529 * query: (q) => q.from({ todos: todosCollection }),
530 * gcTime: 60000
531 * })
532 *
533 * @example
534 * // With query builder and options
535 * const queryBuilder = new Query()
536 * .from({ persons: collection })
537 * .where(({ persons }) => gt(persons.age, 30))
538 * .select(({ persons }) => ({ id: persons.id, name: persons.name }))
539 *
540 * const { data, isReady } = useLiveQuery({
541 * query: queryBuilder,
542 * })
543 *
544 * @example
545 * // Handle all states uniformly
546 * const { data, isLoading, isReady, isError } = useLiveQuery({
547 * query: (q) => q.from({ items: itemCollection })
548 * })
549 *
550 * if (isLoading) return <div>Loading...</div>
551 * if (isError) return <div>Something went wrong</div>
552 * if (!isReady) return <div>Preparing...</div>
553 *
554 * return <div>{data.length} items loaded</div>
555 */
556// Overload 6: Accept config object
557export function useLiveQuery<TContext extends Context>(
558 config: UseLiveQueryConfig<TContext>,
559): {
560 state: Map<string | number, GetResult<TContext>>
561 data: InferResultType<TContext>
562 collection: Collection<GetResult<TContext>, string | number, {}>
563 status: CollectionStatus // Can't be disabled when query always returns a builder
564 isLoading: boolean
565 isReady: boolean
566 persistedStatus: LiveQueryPersistedStatus
567 isPersistedReady: boolean
568 persistedError: unknown | undefined
569 isIdle: boolean
570 isError: boolean
571 isCleanedUp: boolean
572 isEnabled: true // Always true when query always returns a builder
574​
575// Overload 7: Accept config object with a query that can return undefined/null
576export function useLiveQuery<TContext extends Context>(
577 config: ConditionalUseLiveQueryConfig<TContext>,
578): {
579 state: Map<string | number, GetResult<TContext>> | undefined
580 data: InferResultType<TContext> | undefined
581 collection: Collection<GetResult<TContext>, string | number, {}> | undefined
582 status: UseLiveQueryStatus
583 isLoading: boolean
584 isReady: boolean
585 persistedStatus: LiveQueryPersistedStatus
586 isPersistedReady: boolean
587 persistedError: unknown | undefined
588 isIdle: boolean
589 isError: boolean
590 isCleanedUp: boolean
591 isEnabled: boolean
593​
594// Overload 8: Accept config object with legacy deps
595export function useLiveQuery<TContext extends Context>(
596 config: LiveQueryCollectionConfig<TContext>,
597 deps?: Array<unknown>,
598): {
599 state: Map<string | number, GetResult<TContext>>
600 data: InferResultType<TContext>
601 collection: Collection<GetResult<TContext>, string | number, {}>
602 status: CollectionStatus // Can't be disabled when query always returns a builder
603 isLoading: boolean
604 isReady: boolean
605 persistedStatus: LiveQueryPersistedStatus
606 isPersistedReady: boolean
607 persistedError: unknown | undefined
608 isIdle: boolean
609 isError: boolean
610 isCleanedUp: boolean
611 isEnabled: true // Always true when query always returns a builder
613​
614// Overload 9: Accept config object with legacy deps and a query that can return undefined/null
615export function useLiveQuery<TContext extends Context>(
616 config: ConditionalUseLiveQueryConfig<TContext>,
617 deps: Array<unknown>,
618): {
619 state: Map<string | number, GetResult<TContext>> | undefined
620 data: InferResultType<TContext> | undefined
621 collection: Collection<GetResult<TContext>, string | number, {}> | undefined
622 status: UseLiveQueryStatus
623 isLoading: boolean
624 isReady: boolean
625 persistedStatus: LiveQueryPersistedStatus
626 isPersistedReady: boolean
627 persistedError: unknown | undefined
628 isIdle: boolean
629 isError: boolean
630 isCleanedUp: boolean
631 isEnabled: boolean
633​
634/**
635 * Subscribe to an existing live query collection
636 * @param liveQueryCollection - Pre-created live query collection to subscribe to
637 * @returns Object with reactive data, state, and status information
638 * @example
639 * // Using pre-created live query collection
640 * const myLiveQuery = createLiveQueryCollection((q) =>
641 * q.from({ todos: todosCollection }).where(({ todos }) => eq(todos.active, true))
642 * )
643 * const { data, collection } = useLiveQuery(myLiveQuery)
644 *
645 * @example
646 * // Access collection methods directly
647 * const { data, collection, isReady } = useLiveQuery(existingCollection)
648 *
649 * // Use collection for mutations
650 * const handleToggle = (id) => {
651 * collection.update(id, draft => { draft.completed = !draft.completed })
652 * }
653 *
654 * @example
655 * // Handle states consistently
656 * const { data, isLoading, isError } = useLiveQuery(sharedCollection)
657 *
658 * if (isLoading) return <div>Loading...</div>
659 * if (isError) return <div>Error loading data</div>
660 *
661 * return <div>{data.map(item => <Item key={item.id} {...item} />)}</div>
662 */
663// Overload 10: Accept pre-created live query collection
664export function useLiveQuery<
665 TResult extends object,
666 TKey extends string | number,
667 TUtils extends Record<string, any>,
668>(
669 liveQueryCollection: Collection<TResult, TKey, TUtils> & NonSingleResult,
670): {
671 state: Map<TKey, TResult>
672 data: Array<TResult>
673 collection: Collection<TResult, TKey, TUtils>
674 status: CollectionStatus // Can't be disabled for pre-created live query collections
675 isLoading: boolean
676 isReady: boolean
677 persistedStatus: LiveQueryPersistedStatus
678 isPersistedReady: boolean
679 persistedError: unknown | undefined
680 isIdle: boolean
681 isError: boolean
682 isCleanedUp: boolean
683 isEnabled: true // Always true for pre-created live query collections
685​
686// Overload 10: Accept pre-created live query collection with singleResult: true
687export function useLiveQuery<
688 TResult extends object,
689 TKey extends string | number,
690 TUtils extends Record<string, any>,
691>(
692 liveQueryCollection: Collection<TResult, TKey, TUtils> & SingleResult,
693): {
694 state: Map<TKey, TResult>
695 data: TResult | undefined
696 collection: Collection<TResult, TKey, TUtils> & SingleResult
697 status: CollectionStatus // Can't be disabled for pre-created live query collections
698 isLoading: boolean
699 isReady: boolean
700 persistedStatus: LiveQueryPersistedStatus
701 isPersistedReady: boolean
702 persistedError: unknown | undefined
703 isIdle: boolean
704 isError: boolean
705 isCleanedUp: boolean
706 isEnabled: true // Always true for pre-created live query collections
708​
709// Implementation - use function overloads to infer the actual collection type
710export function useLiveQuery(
711 configOrQueryOrCollection: any,
712 deps?: Array<unknown>,
713) {
714 return useLiveQueryImpl(configOrQueryOrCollection, deps)
716​
717/** @internal Shared implementation for the Suspense wrapper. */
718export function useLiveQueryForSuspense(
719 configOrQueryOrCollection: any,
720 deps: Array<unknown> | undefined,
721) {
722 return useLiveQueryImpl(configOrQueryOrCollection, deps, true)
724​
725// What one hook instance keeps across renders. It lives in a single ref
726// slot, so a render neither looks up nor allocates more.
727function createHookInstance(dbClient: DbClient | undefined) {
728 return {
729 collection: null as Collection<object, string | number, {}> | null,
730 deps: null as Array<unknown> | null,
731 config: null as unknown,
732 client: dbClient,
733 legacyUnhashableIdentity: [`legacy-unhashable`] as Array<unknown>,
734 derivedIdentityProfiler: {
735 renderCount: 0,
736 totalMs: 0,
737 maxMs: 0,
738 warned: false,
739 } as DerivedIdentityProfiler,
740 deferredCollections: new Set<
741 CollectionImpl<any, string | number, any, any, any>
742 >(),
743 sourceIds: createSourceIdBindings(),
744 observer: null as LiveQueryObserver<object, string | number> | null,
745 queryHash: undefined as string | undefined,
746 suspenseKey: undefined as string | undefined,
747 identityError: undefined as UnhashableQueryIRError | undefined,
748 subscribe: null as ((onStoreChange: () => void) => () => void) | null,
749 }
751​
752function useLiveQueryImpl(
753 configOrQueryOrCollection: any,
754 deps: Array<unknown> | undefined,
755 forSuspense = false,
756) {
757 const contextDbClient = useOptionalDbClient()
758 // Check if it's already a collection
759 const inputIsCollection = isCollection(configOrQueryOrCollection)
760 const dbClient = inputIsCollection
761 ? contextDbClient
762 : (getExplicitDbClient(configOrQueryOrCollection) ?? contextDbClient)
763 const resolvedDeps = deps ?? []
764​
765 const instanceRef = useRef<ReturnType<typeof createHookInstance> | null>(null)
766 const instance = (instanceRef.current ??= createHookInstance(dbClient))
767 const resumeDeferredCollections = () =>
768 resumeSyncStarts(instance.deferredCollections)
769​
770 const queryKey = !inputIsCollection
771 ? getExplicitQueryKey(configOrQueryOrCollection)
772 : undefined
773 let preparedQueryValue: unknown | typeof unpreparedQueryValue =
774 unpreparedQueryValue
775 let identityDeps: ReadonlyArray<unknown>
776 let streamIdentity: unknown = undefined
777 let identityError: UnhashableQueryIRError | undefined
778​
779 if (queryKey) {
780 identityDeps = queryKey
781 streamIdentity = [`queryKey`, queryKey]
782 } else if (deps !== undefined) {
783 identityDeps = resolvedDeps
784 // Deps decide reuse. Only hydration and Suspense read the query hash; the
785 // development warning about unhashable queries still derives it.
786 if (
787 dbClient ||
788 forSuspense ||
789 (shouldWarnInDevelopment(`TANSTACK_DB_DISABLE_QUERY_IDENTITY_WARNINGS`) &&
790 process.env.NODE_ENV !== `production`)
791 )
792 try {
793 preparedQueryValue = prepareQueryValue(
794 configOrQueryOrCollection,
795 dbClient,
796 instance.deferredCollections,
797 )
798 streamIdentity = [
799 `deps`,
800 resolvedDeps,
801 getPreparedLiveQueryIdentity(preparedQueryValue),
802 ]
803 } catch (error) {
804 if (!(error instanceof UnhashableQueryIRError)) throw error
805 warnUnhashableDerivedIdentity(error)
806 identityError = error
807 }
808 } else if (inputIsCollection) {
809 identityDeps = []
810 streamIdentity = [`collection`, configOrQueryOrCollection.id]
811 } else {
812 const preparation = prepareDerivedQuery(
813 configOrQueryOrCollection,
814 dbClient,
815 instance.derivedIdentityProfiler,
816 instance.deferredCollections,
817 )
818 preparedQueryValue = preparation.value
819 if (preparation.status === `hashable`) {
820 identityDeps = preparation.identityDeps
821 streamIdentity = preparation.identityDeps
822 } else {
823 warnUnhashableDerivedIdentity(preparation.error)
824 identityDeps = instance.legacyUnhashableIdentity
825 identityError = preparation.error
826 }
827 }
828​
829 let queryHash: string | undefined
830 if (streamIdentity !== undefined) {
831 try {
832 queryHash = getStableValueHash(streamIdentity, `queryKey`)
833 } catch (error) {
834 if (error instanceof UnhashableQueryIRError) {
835 if (queryKey !== undefined) throw error
836 identityError = error
837 } else {
838 throw error
839 }
840 }
841 }
842​
843 if (deps !== undefined) {
844 warnDeprecatedDepsArray()
845 }
846​
847 if (
848 queryKey === undefined &&
849 deps === undefined &&
850 preparedQueryValue !== unpreparedQueryValue
851 ) {
852 claimSourceIds(
853 instance.sourceIds,
854 preparedQueryValue,
855 dbClient,
856 `useLiveQuery`,
857 resumeDeferredCollections,
858 )
859 }
860​
861 const canReuseSuspenseKey =
862 forSuspense &&
863 !inputIsCollection &&
864 queryHash !== undefined &&
865 instance.collection !== null &&
866 instance.client === dbClient &&
867 instance.queryHash === queryHash &&
868 instance.suspenseKey !== undefined
869​
870 if (
871 forSuspense &&
872 !inputIsCollection &&
873 queryHash &&
874 !canReuseSuspenseKey &&
875 preparedQueryValue === unpreparedQueryValue
876 ) {
877 preparedQueryValue = prepareQueryValue(
878 configOrQueryOrCollection,
879 dbClient,
880 instance.deferredCollections,
881 )
882 }
883​
884 const suspenseKey =
885 queryHash && forSuspense && !inputIsCollection
886 ? canReuseSuspenseKey
887 ? instance.suspenseKey
888 : getSourceQualifiedSuspenseKey(preparedQueryValue, queryHash, dbClient)
889 : queryHash
890​
891 const suspenseCollections =
892 forSuspense && !inputIsCollection && suspenseKey
893 ? getSuspenseCollections(dbClient)
894 : undefined
895 const suspenseEntry = suspenseKey
896 ? suspenseCollections?.get(suspenseKey)
897 : undefined
898 const suspenseCollection = suspenseEntry?.collection
899​
900 const identityChanged =
901 instance.deps === null ||
902 (deps !== undefined
903 ? instance.deps.length !== identityDeps.length ||
904 instance.deps.some((dep, index) => dep !== identityDeps[index])
905 : !deepEquals(instance.deps, identityDeps))
906​
907 // Check if we need to create/recreate the collection
908 const needsNewCollection =
909 !instance.collection ||
910 (inputIsCollection && instance.config !== configOrQueryOrCollection) ||
911 (!inputIsCollection && (instance.client !== dbClient || identityChanged))
912​
913 if (needsNewCollection) {
914 if (inputIsCollection) {
915 // Warn when passing a collection directly with on-demand sync mode
916 // In on-demand mode, data is only loaded when queries with predicates request it
917 // Passing the collection directly doesn't provide any predicates, so no data loads
918 const syncMode = (
919 configOrQueryOrCollection as { config?: { syncMode?: string } }
920 ).config?.syncMode
921 if (
922 syncMode === `on-demand` &&
923 shouldWarnInDevelopment(
924 `TANSTACK_DB_DISABLE_QUERY_IDENTITY_WARNINGS`,
925 ) &&
926 process.env.NODE_ENV !== `production`
927 ) {
928 console.warn(
929 `[useLiveQuery] Warning: Passing a collection with syncMode "on-demand" directly to useLiveQuery ` +
930 `will not load any data. In on-demand mode, data is only loaded when queries with predicates request it.\n\n` +
931 `Instead, use a query builder function:\n` +
932 ` const { data } = useLiveQuery({ query: (q) => q.from({ c: myCollection }).select(({ c }) => c) })\n\n` +
933 `Or switch to syncMode "eager" if you want all data to sync automatically.`,
934 )
935 }
936 // It's already a collection, ensure sync is started for React hooks
937 configOrQueryOrCollection.startSyncImmediate()
938 instance.collection = configOrQueryOrCollection
939 instance.config = configOrQueryOrCollection
940 } else {
941 if (suspenseCollection) {
942 instance.collection = suspenseCollection
943 } else {
944 if (preparedQueryValue === unpreparedQueryValue) {
945 preparedQueryValue = prepareQueryValue(
946 configOrQueryOrCollection,
947 dbClient,
948 instance.deferredCollections,
949 )
950 }
951 if (!dbClient) {
952 getPreparedSources(preparedQueryValue, dbClient, `useLiveQuery`)
953 }
954 instance.collection = resolveLiveQueryValue(preparedQueryValue, {
955 gcTime: forSuspense
956 ? DEFAULT_SUSPENSE_GC_TIME_MS
957 : DEFAULT_GC_TIME_MS,
958 // Hydration and Suspense key the live-query Collection by identity.
959 pool: !forSuspense && !dbClient,
960 // Without a DbClient, Suspense starts it through a preload below.
961 startSync: !forSuspense || dbClient !== undefined,
962 }) as SuspenseCollection | null
963 if (suspenseCollections && suspenseKey && instance.collection) {
964 const collection = instance.collection
965 const removeCleanupListener = collection.on(`status:cleaned-up`, () =>
966 releaseSuspenseCollection(
967 suspenseCollections,
968 suspenseKey,
969 collection,
970 ),
971 )
972 const removeErrorListener = collection.on(`status:error`, () => {
973 // Keep the failed collection through React's immediate retry so
974 // the hook can throw its actual load error to an ErrorBoundary.
975 // Retire it afterward so a later boundary reset starts fresh.
976 setTimeout(
977 () =>
978 releaseSuspenseCollection(
979 suspenseCollections,
980 suspenseKey,
981 collection,
982 ),
983 0,
984 )
985 })
986 const entry: SuspenseCollectionEntry = {
987 collection,
988 removeStatusListeners: () => {
989 removeCleanupListener()
990 removeErrorListener()
991 },
992 }
993 suspenseCollections.set(suspenseKey, entry)
994 }
995 }
996 instance.config = configOrQueryOrCollection
997 instance.deps = [...identityDeps]
998 }
999 instance.client = dbClient
1000 instance.queryHash = queryHash
1001 instance.suspenseKey = suspenseKey
1002 instance.identityError = identityError
1004​
1005 // Recreate the observer when the underlying collection changes. The observer
1006 // is not disposed explicitly here or on unmount: `useSyncExternalStore`
1007 // unsubscribes it when the subscribe changes or the component unmounts, which
1008 // detaches the collection subscription; the observer is then GC'd. (An unmount
1009 // effect that disposed it would misfire under StrictMode/offscreen effect
1010 // replay, leaving a disposed observer in the ref.)
1011 if (needsNewCollection) {
1012 // Defer the initial notify: useSyncExternalStore must not be notified
1013 // synchronously during subscribe.
1014 // Wholesale mode: React re-reads getSnapshot() on notify, keeps the
1015 // hook's pre-observer loading policy, and — because wholesale delivers
1016 // nothing synchronously during subscribe — never notifies
1017 // useSyncExternalStore inside its own subscribe call.
1018 instance.observer = createLiveQueryObserver(instance.collection, {
1019 mode: `wholesale`,
1020 client: dbClient,
1021 queryHash: instance.queryHash,
1022 onPreload: resumeDeferredCollections,
1023 })
1025 const observer = instance.observer!
1026 // A Suspense render asks for its data. Preloading starts the sync run, so a
1027 // source that already holds the rows makes it ready before the snapshot is
1028 // read instead of suspending once. useLiveSuspenseQuery surfaces failures.
1029 // A DbClient defers source starts past render and owns its streamed query.
1030 if (
1031 forSuspense &&
1032 !dbClient &&
1033 (instance.collection?.status === `idle` ||
1034 instance.collection?.status === `cleaned-up`)
1035 ) {
1036 observer.preloadForInitialRender().catch(() => {})
1038​
1039 // Stable subscribe bound to the current observer; the observer owns the
1040 // subscription, ready-race, and disposal.
1041 if (!instance.subscribe || needsNewCollection) {
1042 instance.subscribe = (onStoreChange: () => void) => {
1043 const unsubscribe = observer.subscribe(onStoreChange)
1044 resumeDeferredCollections()
1045 return unsubscribe
1048​
1049 const returned = useSyncExternalStore(
1050 instance.subscribe,
1051 () => observer.getSnapshot(),
1052 () => observer.getServerSnapshot(),
1054 // Only useLiveSuspenseQuery reads this, and it costs a define per render.
1055 if (forSuspense) {
1056 setLiveQueryResultInfo(returned, {
1057 client: dbClient,
1058 queryHash: instance.queryHash,
1059 identityError: instance.identityError,
1060 observer,
1061 })
1063 return returned as any