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