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

overview.md

163 lines4.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​
20### useLiveQuery
21​
22The `useLiveQuery` hook creates a live query that automatically updates your component when data changes:
23​
24```tsx
25import { useLiveQuery, eq } from '@tanstack/react-db'
26​
27function TodoList() {
28 const { data, isLoading } = useLiveQuery((q) =>
29 q.from({ todos: todosCollection })
30 .where(({ todos }) => eq(todos.completed, false))
31 .select(({ todos }) => ({ id: todos.id, text: todos.text }))
32 )
33​
34 if (isLoading) return <div>Loading...</div>
35​
36 return (
37 <ul>
38 {data.map(todo => <li key={todo.id}>{todo.text}</li>)}
39 </ul>
40 )
42```
43​
44### Dependency Arrays
45​
46All query hooks (`useLiveQuery`, `useLiveInfiniteQuery`, `useLiveSuspenseQuery`) accept an optional dependency array as their last parameter. This array works similarly to React's `useEffect` dependencies - when any value in the array changes, the query is recreated and re-executed.
47​
48#### When to Use Dependency Arrays
49​
50Use dependency arrays when your query depends on external reactive values (props, state, or other hooks):
51​
52```tsx
53function FilteredTodos({ minPriority }: { minPriority: number }) {
54 const { data } = useLiveQuery(
55 (q) => q.from({ todos: todosCollection })
56 .where(({ todos }) => gt(todos.priority, minPriority)),
57 [minPriority] // Re-run when minPriority changes
58 )
59​
60 return <div>{data.length} high-priority todos</div>
62```
63​
64#### What Happens When Dependencies Change
65​
66When a dependency value changes:
671. The previous live query collection is cleaned up
682. A new query is created with the updated values
693. The component re-renders with the new data
704. The hook suspends (for `useLiveSuspenseQuery`) or shows loading state
71​
72#### Best Practices
73​
74**Include all external values used in the query:**
75​
76```tsx
77// Good - all external values in deps
78const { data } = useLiveQuery(
79 (q) => q.from({ todos: todosCollection })
80 .where(({ todos }) => and(
81 eq(todos.userId, userId),
82 eq(todos.status, status)
83 )),
84 [userId, status]
86​
87// Bad - missing dependencies
88const { data } = useLiveQuery(
89 (q) => q.from({ todos: todosCollection })
90 .where(({ todos }) => eq(todos.userId, userId)),
91 [] // Missing userId!
93```
94​
95**Empty array for static queries:**
96​
97```tsx
98// No external dependencies - query never changes
99const { data } = useLiveQuery(
100 (q) => q.from({ todos: todosCollection }),
101 []
103```
104​
105**Omit the array for queries with no external dependencies:**
106​
107```tsx
108// Same as above - no deps needed
109const { data } = useLiveQuery(
110 (q) => q.from({ todos: todosCollection })
112```
113​
114### useLiveInfiniteQuery
115​
116For paginated data with live updates, use `useLiveInfiniteQuery`:
117​
118```tsx
119const { data, pages, fetchNextPage, hasNextPage } = useLiveInfiniteQuery(
120 (q) => q
121 .from({ posts: postsCollection })
122 .where(({ posts }) => eq(posts.category, category))
123 .orderBy(({ posts }) => posts.createdAt, 'desc'),
124 {
125 pageSize: 20,
126 getNextPageParam: (lastPage, allPages) =>
127 lastPage.length === 20 ? allPages.length : undefined
128 },
129 [category] // Re-run when category changes
131```
132​
133**Note:** The dependency array is only available when using the query function variant, not when passing a pre-created collection.
134​
135### useLiveSuspenseQuery
136​
137For React Suspense integration, use `useLiveSuspenseQuery`:
138​
139```tsx
140function TodoList({ filter }: { filter: string }) {
141 const { data } = useLiveSuspenseQuery(
142 (q) => q.from({ todos: todosCollection })
143 .where(({ todos }) => eq(todos.filter, filter)),
144 [filter] // Re-suspends when filter changes
145 )
146​
147 return (
148 <ul>
149 {data.map(todo => <li key={todo.id}>{todo.text}</li>)}
150 </ul>
151 )
153​
154function App() {
155 return (
156 <Suspense fallback={<div>Loading...</div>}>
157 <TodoList filter="active" />
158 </Suspense>
159 )
161```
162​
163When dependencies change, `useLiveSuspenseQuery` will re-suspend, showing your Suspense fallback until the new data is ready.