Open History to see the last commit
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>
31)
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 )
56}
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>
73}
74```
75
76#### Collection Hooks
77
78`useLiveQuery` resolves collection descriptors from `DbProvider` automatically. Create small collection hooks when components need imperative collection methods like `insert`, `update`, `delete`, or `preload`:
79
80```tsx
81function useTodoCollection() {
82 return useDbClient().collection(todoCollection)
83}
84```
85
86#### When to Use Query Keys
87
88Use `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`:
89
90```tsx
91function SearchTodos({ search }: { search: string }) {
92 const { data } = useLiveQuery({
93 queryKey: [todoCollection.id, 'search', search],
94 query: (q) => q.from({ todos: todoCollection })
95 .fn.where(({ todos }) =>
96 todos.text.toLowerCase().includes(search.toLowerCase())
97 ),
98 })
99
100 return <div>{data.length} matching todos</div>
101}
102```
103
104Before 1.0, an unhashable query warns in development and keeps its legacy
105mount-stable identity. The query still runs, but captured values inside opaque
106logic only become reactive when they are represented in `queryKey`. In 1.0, an
107unhashable query without `queryKey` will throw. If deriving identity becomes
108expensive across renders, the hook warns once and suggests adding a `queryKey`
109as a performance escape hatch.
110
111#### What Happens When Identity Changes
112
113When the derived identity or explicit query key changes:
1141. The previous live query collection is cleaned up
1152. A new query is created with the updated values
1163. The component re-renders with the new data
1174. The hook suspends (for `useLiveSuspenseQuery`) or shows loading state
118
119#### Best Practices
120
121**Use structured expressions when possible:**
122
123```tsx
124// Good - DB can derive identity from this structured IR
125const { data } = useLiveQuery({
126 query: (q) => q.from({ todos: todoCollection })
127 .where(({ todos }) => and(
128 eq(todos.userId, userId),
129 eq(todos.status, status)
130 )),
131})
132```
133
134**Add a query key for opaque runtime logic:**
135
136```tsx
137const { data } = useLiveQuery({
138 queryKey: [todoCollection.id, 'by-user-fn', userId],
139 query: (q) => q.from({ todos: todoCollection })
140 .fn.where(({ todos }) => todos.userId === userId),
141})
142```
143
144**Omit query keys for static structured queries:**
145
146```tsx
147const { data } = useLiveQuery({
148 query: (q) => q.from({ todos: todoCollection }),
149})
150```
151
152Dependency arrays are still accepted for backwards compatibility, but they warn in development and will be removed in 1.0.
153
154For SSR setup, collection hydration, and migration details, see the [SSR and Hydration guide](../../guides/ssr.md).
155
156### useLiveInfiniteQuery
157
158For paginated data with live updates, use `useLiveInfiniteQuery`:
159
160```tsx
161const { data, pages, fetchNextPage, hasNextPage } = useLiveInfiniteQuery(
162 (q) => q
163 .from({ posts: postsCollection })
164 .where(({ posts }) => eq(posts.category, category))
165 .orderBy(({ posts }) => posts.createdAt, 'desc'),
166 {
167 pageSize: 20,
168 getNextPageParam: (lastPage, allPages) =>
169 lastPage.length === 20 ? allPages.length : undefined
170 }
171)
172```
173
174`fetchNextPage()` returns a promise that resolves after the page request settles. Failures are exposed through the returned `error` value and do not reject the promise.
175
176The deprecated dependency array is only available when using the query function variant, not when passing a pre-created collection.
177
178### useLiveSuspenseQuery
179
180For React Suspense integration, use `useLiveSuspenseQuery`:
181
182```tsx
183function TodoList({ filter }: { filter: string }) {
184 const { data } = useLiveSuspenseQuery({
185 query: (q) => q.from({ todos: todoCollection })
186 .where(({ todos }) => eq(todos.filter, filter)),
187 })
188
189 return (
190 <ul>
191 {data.map(todo => <li key={todo.id}>{todo.text}</li>)}
192 </ul>
193 )
194}
195
196function App() {
197 return (
198 <Suspense fallback={<div>Loading...</div>}>
199 <TodoList filter="active" />
200 </Suspense>
201 )
202}
203```
204
205When the derived identity or explicit `queryKey` changes, `useLiveSuspenseQuery` will re-suspend, showing your Suspense fallback until the new data is ready.