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