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