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