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

useLiveQuery.ts

1,038 lines32.3 KB

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