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

overview.md

221 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 derived-identity queries in one mounted hook and `DbClient` scope, a source
77Collection ID must keep referring to the same Collection object. If a render
78supplies a different source object with a previously used ID, the hook throws
79instead of returning rows from the old source. To reuse an ID within that hook,
80unmount it, clean up its source and client scope, then mount the replacement.
81Separate hooks and independent client scopes can use the same ID.
82​
83#### Collection Hooks
84​
85`useLiveQuery` resolves collection descriptors from `DbProvider` automatically. Create small collection hooks when components need imperative collection methods like `insert`, `update`, `delete`, or `preload`:
86​
87```tsx
88function useTodoCollection() {
89 return useDbClient().collection(todoCollection)
91```
92​
93#### When to Use Query Keys
94​
95Use `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`:
96​
97```tsx
98function SearchTodos({ search }: { search: string }) {
99 const { data } = useLiveQuery({
100 queryKey: [todoCollection.id, 'search', search],
101 query: (q) => q.from({ todos: todoCollection })
102 .fn.where(({ todos }) =>
103 todos.text.toLowerCase().includes(search.toLowerCase())
104 ),
105 })
106​
107 return <div>{data.length} matching todos</div>
109```
110​
111An explicit `queryKey` is the caller's identity contract. If its source object
112changes, change the key too, even when the source ID stays the same. Use a
113primitive scope token in the key; Collection objects cannot be hashed there.
114​
115Before 1.0, an unhashable query warns in development and keeps its legacy
116mount-stable identity. The query still runs, but captured values inside opaque
117logic only become reactive when they are represented in `queryKey`. In 1.0, an
118unhashable query without `queryKey` will throw. If deriving identity becomes
119expensive across renders, the hook warns once and suggests adding a `queryKey`
120as a performance escape hatch.
121​
122#### What Happens When Identity Changes
123​
124When the derived identity or explicit query key changes:
1251. The previous live query collection is cleaned up
1262. A new query is created with the updated values
1273. The component re-renders with the new data
1284. The hook suspends (for `useLiveSuspenseQuery`) or shows loading state
129​
130#### Best Practices
131​
132**Use structured expressions when possible:**
133​
134```tsx
135// Good - DB can derive identity from this structured IR
136const { data } = useLiveQuery({
137 query: (q) => q.from({ todos: todoCollection })
138 .where(({ todos }) => and(
139 eq(todos.userId, userId),
140 eq(todos.status, status)
141 )),
142})
143```
144​
145**Add a query key for opaque runtime logic:**
146​
147```tsx
148const { data } = useLiveQuery({
149 queryKey: [todoCollection.id, 'by-user-fn', userId],
150 query: (q) => q.from({ todos: todoCollection })
151 .fn.where(({ todos }) => todos.userId === userId),
152})
153```
154​
155**Omit query keys for static structured queries:**
156​
157```tsx
158const { data } = useLiveQuery({
159 query: (q) => q.from({ todos: todoCollection }),
160})
161```
162​
163Dependency arrays are still accepted for backwards compatibility, but they warn in development and will be removed in 1.0.
164​
165For SSR setup, collection hydration, and migration details, see the [SSR and Hydration guide](../../guides/ssr.md).
166​
167### useLiveInfiniteQuery
168​
169For paginated data with live updates, use `useLiveInfiniteQuery`:
170​
171```tsx
172const { data, pages, fetchNextPage, hasNextPage } = useLiveInfiniteQuery(
173 (q) => q
174 .from({ posts: postsCollection })
175 .where(({ posts }) => eq(posts.category, category))
176 .orderBy(({ posts }) => posts.createdAt, 'desc'),
177 {
178 pageSize: 20,
179 }
181```
182​
183`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.
184​
185This hook widens an ordered live query; it is not TanStack Query's
186`useInfiniteQuery`. `getNextPageParam` was previously ignored and is now rejected.
187`initialPageParam` only labels the returned pages; it does not set a server cursor
188or skip remote rows. For server pagination, use an on-demand Query Collection
189whose `queryFn` fulfills `meta.loadSubsetOptions`. See the
190[server pagination guide](../../collections/query-collection.md#server-pagination-with-live-queries).
191​
192The deprecated dependency array is only available when using the query function variant, not when passing a pre-created collection.
193​
194### useLiveSuspenseQuery
195​
196For React Suspense integration, use `useLiveSuspenseQuery`:
197​
198```tsx
199function TodoList({ filter }: { filter: string }) {
200 const { data } = useLiveSuspenseQuery({
201 query: (q) => q.from({ todos: todoCollection })
202 .where(({ todos }) => eq(todos.filter, filter)),
203 })
204​
205 return (
206 <ul>
207 {data.map(todo => <li key={todo.id}>{todo.text}</li>)}
208 </ul>
209 )
211​
212function App() {
213 return (
214 <Suspense fallback={<div>Loading...</div>}>
215 <TodoList filter="active" />
216 </Suspense>
217 )
219```
220​
221When the derived identity or explicit `queryKey` changes, `useLiveSuspenseQuery` will re-suspend, showing your Suspense fallback until the new data is ready.