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