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