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