Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

overview.md

222 lines7.2 KB

1---
2title: TanStack DB React Adapter
3id: adapter
4---
5​
6## Installation
7​
8```sh
9npm install @tanstack/react-db
10```
11​
12## React Hooks
13​
14See the [React Functions Reference](./reference/index.md) to see the full list of hooks available in the React Adapter.
15​
16For comprehensive documentation on writing queries (filtering, joins, aggregations, etc.), see the [Live Queries Guide](../../guides/live-queries).
17​
18## Basic Usage
19​
20Create a `DbClient` and provide it to your React tree:
21​
22```tsx
23import { DbClient, DbProvider } from '@tanstack/react-db'
24​
25const dbClient = new DbClient()
26​
27root.render(
28 <DbProvider client={dbClient}>
29 <App />
30 </DbProvider>
32```
33​
34### useLiveQuery
35​
36The `useLiveQuery` hook creates a live query that automatically updates your component when data changes:
37​
38```tsx
39import { and, eq, gt, useDbClient, useLiveQuery } from '@tanstack/react-db'
40​
41function TodoList() {
42 const { data, isLoading } = useLiveQuery({
43 query: (q) =>
44 q.from({ todos: todoCollection })
45 .where(({ todos }) => eq(todos.completed, false))
46 .select(({ todos }) => ({ id: todos.id, text: todos.text })),
47 })
48​
49 if (isLoading) return <div>Loading...</div>
50​
51 return (
52 <ul>
53 {data.map(todo => <li key={todo.id}>{todo.text}</li>)}
54 </ul>
55 )
57```
58​
59### Query Identity
60​
61React live query hooks derive the live query identity from structured query IR by default. The hook runs the query builder, normalizes the resulting IR, and uses that as the identity. When the derived identity changes, the old live query collection is cleaned up and a new one is created.
62​
63That means normal structured queries do not need a separate `queryKey`. Collection descriptors provide stable collection IDs, and captured values inside structured expressions become part of the derived identity:
64​
65```tsx
66function FilteredTodos({ minPriority }: { minPriority: number }) {
67 const { data } = useLiveQuery({
68 query: (q) => q.from({ todos: todoCollection })
69 .where(({ todos }) => gt(todos.priority, minPriority)),
70 })
71​
72 return <div>{data.length} high-priority todos</div>
74```
75​
76For queries without `queryKey` in one mounted hook and `DbClient` scope, a
77source Collection ID must keep referring to the same Collection object. If a
78render supplies a different source object with a previously used ID, the hook
79throws `SourceCollectionIdReuseError` instead of returning rows from the old
80source. To reuse an ID within that hook,
81unmount it, clean up its source and client scope, then mount the replacement.
82Separate hooks and independent client scopes can use the same ID.
83​
84#### Collection Hooks
85​
86`useLiveQuery` resolves collection descriptors from `DbProvider` automatically. Create small collection hooks when components need imperative collection methods like `insert`, `update`, `delete`, or `preload`:
87​
88```tsx
89function useTodoCollection() {
90 return useDbClient().collection(todoCollection)
92```
93​
94#### When to Use Query Keys
95​
96Use `queryKey` only when DB cannot derive identity from structured IR, or when you intentionally want to avoid deriving identity on a hot render path. The common case is a functional query variant such as `.fn.where`, `.fn.select`, or `.fn.having`:
97​
98```tsx
99function SearchTodos({ search }: { search: string }) {
100 const { data } = useLiveQuery({
101 queryKey: [todoCollection.id, 'search', search],
102 query: (q) => q.from({ todos: todoCollection })
103 .fn.where(({ todos }) =>
104 todos.text.toLowerCase().includes(search.toLowerCase())
105 ),
106 })
107​
108 return <div>{data.length} matching todos</div>
110```
111​
112An explicit `queryKey` is the caller's identity contract. If its source object
113changes, change the key too, even when the source ID stays the same. Use a
114primitive scope token in the key; Collection objects cannot be hashed there.
115​
116An unhashable query without `queryKey` throws `UnhashableQueryIRError`, so
117represent the values that opaque logic captures in the key. An empty
118`queryKey` counts as none, as it does for a `DbClient` preload. A dependency
119array does not replace `queryKey` for such a query. If deriving identity becomes
120expensive across renders, the hook warns once and suggests adding a `queryKey`
121as a performance escape hatch.
122​
123#### What Happens When Identity Changes
124​
125When the derived identity or explicit query key changes:
1261. The previous live query collection is cleaned up
1272. A new query is created with the updated values
1283. The component re-renders with the new data
1294. The hook suspends (for `useLiveSuspenseQuery`) or shows loading state
130​
131#### Best Practices
132​
133**Use structured expressions when possible:**
134​
135```tsx
136// Good - DB can derive identity from this structured IR
137const { data } = useLiveQuery({
138 query: (q) => q.from({ todos: todoCollection })
139 .where(({ todos }) => and(
140 eq(todos.userId, userId),
141 eq(todos.status, status)
142 )),
143})
144```
145​
146**Add a query key for opaque runtime logic:**
147​
148```tsx
149const { data } = useLiveQuery({
150 queryKey: [todoCollection.id, 'by-user-fn', userId],
151 query: (q) => q.from({ todos: todoCollection })
152 .fn.where(({ todos }) => todos.userId === userId),
153})
154```
155​
156**Omit query keys for static structured queries:**
157​
158```tsx
159const { data } = useLiveQuery({
160 query: (q) => q.from({ todos: todoCollection }),
161})
162```
163​
164Dependency arrays are still accepted for backwards compatibility, but they warn in development and will be removed in 1.0.
165​
166For SSR setup, collection hydration, and migration details, see the [SSR and Hydration guide](../../guides/ssr.md).
167​
168### useLiveInfiniteQuery
169​
170For paginated data with live updates, use `useLiveInfiniteQuery`:
171​
172```tsx
173const { data, pages, fetchNextPage, hasNextPage } = useLiveInfiniteQuery(
174 (q) => q
175 .from({ posts: postsCollection })
176 .where(({ posts }) => eq(posts.category, category))
177 .orderBy(({ posts }) => posts.createdAt, 'desc'),
178 {
179 pageSize: 20,
180 }
182```
183​
184`fetchNextPage()` returns a promise that resolves after the page request settles. A failed page load does not reject the promise or change `status`; it appears as a request error in the returned `health` tree.
185​
186This hook widens an ordered live query; it is not TanStack Query's
187`useInfiniteQuery`. `getNextPageParam` was previously ignored and is now rejected.
188`initialPageParam` only labels the returned pages; it does not set a server cursor
189or skip remote rows. For server pagination, use an on-demand Query Collection
190whose `queryFn` fulfills `meta.loadSubsetOptions`. See the
191[server pagination guide](../../collections/query-collection.md#server-pagination-with-live-queries).
192​
193The deprecated dependency array is only available when using the query function variant, not when passing a pre-created collection.
194​
195### useLiveSuspenseQuery
196​
197For React Suspense integration, use `useLiveSuspenseQuery`:
198​
199```tsx
200function TodoList({ filter }: { filter: string }) {
201 const { data } = useLiveSuspenseQuery({
202 query: (q) => q.from({ todos: todoCollection })
203 .where(({ todos }) => eq(todos.filter, filter)),
204 })
205​
206 return (
207 <ul>
208 {data.map(todo => <li key={todo.id}>{todo.text}</li>)}
209 </ul>
210 )
212​
213function App() {
214 return (
215 <Suspense fallback={<div>Loading...</div>}>
216 <TodoList filter="active" />
217 </Suspense>
218 )
220```
221​
222When the derived identity or explicit `queryKey` changes, `useLiveSuspenseQuery` will re-suspend, showing your Suspense fallback until the new data is ready.