Open History to see the last commit
1---
2title: Quick Start
3id: quick-start
4---
5
6TanStack DB is the reactive client-first store for your API. Stop building custom endpoints for every view—query your data however your components need it. This example will show you how to:
7
8- **Load data** into collections using TanStack Query
9- **Query data** with blazing-fast live queries
10- **Mutate data** with instant optimistic updates
11
12```tsx
13import {
14 DbClient,
15 DbProvider,
16 collectionOptions,
17 eq,
18 useDbClient,
19 useLiveQuery,
20} from '@tanstack/react-db'
21import { QueryClient } from '@tanstack/query-core'
22import { queryCollectionOptions } from '@tanstack/query-db-collection'
23
24const queryClient = new QueryClient()
25const dbClient = new DbClient({ queryClient })
26
27// Define a stable collection descriptor that loads data using TanStack Query
28const todoCollection = collectionOptions('todos', (client) =>
29 queryCollectionOptions<{ id: string; text: string; completed: boolean; createdAt: string }>({
30 id: 'todos',
31 queryKey: ['todos'],
32 queryClient: client.requireDependency<QueryClient>('queryClient'),
33 queryFn: async () => {
34 const response = await fetch('/api/todos')
35 return response.json()
36 },
37 getKey: (item) => item.id,
38 onUpdate: async ({ transaction, collection }) => {
39 const { original, modified } = transaction.mutations[0]
40 await fetch(`/api/todos/${original.id}`, {
41 method: 'PUT',
42 body: JSON.stringify(modified),
43 })
44 await collection.utils.refetch()
45 },
46 })
47)
48
49function useTodoCollection() {
50 return useDbClient().collection(todoCollection)
51}
52
53function Todos() {
54 const todosCollection = useTodoCollection()
55
56 // Live query that updates automatically when data changes
57 const { data: todos } = useLiveQuery({
58 query: (q) =>
59 q.from({ todo: todoCollection })
60 .where(({ todo }) => eq(todo.completed, false))
61 .orderBy(({ todo }) => todo.createdAt, 'desc'),
62 })
63
64 const toggleTodo = (todo: { id: string }) => {
65 // Instantly applies optimistic state, then syncs to server
66 todosCollection.update(todo.id, (draft) => {
67 draft.completed = !draft.completed
68 })
69 }
70
71 return (
72 <ul>
73 {todos.map((todo) => (
74 <li key={todo.id} onClick={() => toggleTodo(todo)}>
75 {todo.text}
76 </li>
77 ))}
78 </ul>
79 )
80}
81
82function App() {
83 return (
84 <DbProvider client={dbClient}>
85 <Todos />
86 </DbProvider>
87 )
88}
89```
90
91You now have collections, live queries, and optimistic mutations! Let's break this down further.
92
93If you are building with SSR, see the [SSR and Hydration guide](./guides/ssr.md)
94after this quick start. The short version is that SSR apps use stable
95`collectionOptions(...)` descriptors, materialize them through a request-scoped
96`DbClient` on the server, then hydrate a browser `DbClient` with explicit
97collection rows or a preloaded live-query result before React hooks read from
98DB.
99
100## Installation
101
102```bash
103npm install @tanstack/react-db @tanstack/query-db-collection @tanstack/query-core
104```
105
106## 1. Create a Collection
107
108Collections store your data and handle persistence. The `queryCollectionOptions` loads data using TanStack Query and defines mutation handlers for server sync:
109
110```tsx
111const todoCollection = collectionOptions('todos', (client) =>
112 queryCollectionOptions<{ id: string; text: string; completed: boolean; createdAt: string }>({
113 id: 'todos',
114 queryKey: ['todos'],
115 queryClient: client.requireDependency<QueryClient>('queryClient'),
116 queryFn: async () => {
117 const response = await fetch('/api/todos')
118 return response.json()
119 },
120 getKey: (item) => item.id,
121 // Handle all CRUD operations
122 onInsert: async ({ transaction, collection }) => {
123 const { modified: newTodo } = transaction.mutations[0]
124 await fetch('/api/todos', {
125 method: 'POST',
126 body: JSON.stringify(newTodo),
127 })
128 await collection.utils.refetch()
129 },
130 onUpdate: async ({ transaction, collection }) => {
131 const { original, modified } = transaction.mutations[0]
132 await fetch(`/api/todos/${original.id}`, {
133 method: 'PUT',
134 body: JSON.stringify(modified),
135 })
136 await collection.utils.refetch()
137 },
138 onDelete: async ({ transaction, collection }) => {
139 const { original } = transaction.mutations[0]
140 await fetch(`/api/todos/${original.id}`, { method: 'DELETE' })
141 await collection.utils.refetch()
142 },
143 })
144)
145```
146
147The `queryKey` above is TanStack Query's cache key for loading the collection.
148React live queries below derive their own identity from structured query IR.
149
150## 2. Materialize the Collection
151
152Use the `DbClient` from context to materialize the descriptor. A tiny collection hook keeps components from repeating the client lookup:
153
154```tsx
155function useTodoCollection() {
156 return useDbClient().collection(todoCollection)
157}
158```
159
160## 3. Query with Live Queries
161
162Live queries reactively update when data changes. They support filtering, sorting, joins, and transformations. React hooks derive query identity from the structured query by default, so normal builder queries do not need a separate `queryKey`:
163
164```tsx
165function TodoList() {
166 // Basic filtering and sorting
167 const { data: incompleteTodos } = useLiveQuery({
168 query: (q) =>
169 q.from({ todo: todoCollection })
170 .where(({ todo }) => eq(todo.completed, false))
171 .orderBy(({ todo }) => todo.createdAt, 'desc'),
172 })
173
174 // Transform the data
175 const { data: todoSummary } = useLiveQuery({
176 query: (q) =>
177 q.from({ todo: todoCollection })
178 .select(({ todo }) => ({
179 id: todo.id,
180 summary: `${todo.text} (${todo.completed ? 'done' : 'pending'})`,
181 priority: todo.priority || 'normal'
182 })),
183 })
184
185 return <div>{/* Render todos */}</div>
186}
187```
188
189## 4. Optimistic Mutations
190
191Mutations apply instantly and sync to your server. If the server request fails, changes automatically roll back:
192
193```tsx
194function TodoActions({ todo }) {
195 const todosCollection = useTodoCollection()
196
197 const addTodo = () => {
198 todosCollection.insert({
199 id: crypto.randomUUID(),
200 text: 'New todo',
201 completed: false,
202 createdAt: new Date(),
203 })
204 }
205
206 const toggleComplete = () => {
207 todosCollection.update(todo.id, (draft) => {
208 draft.completed = !draft.completed
209 })
210 }
211
212 const updateText = (newText) => {
213 todosCollection.update(todo.id, (draft) => {
214 draft.text = newText
215 })
216 }
217
218 const deleteTodo = () => {
219 todosCollection.delete(todo.id)
220 }
221
222 return (
223 <div>
224 <button onClick={addTodo}>Add Todo</button>
225 <button onClick={toggleComplete}>Toggle</button>
226 <button onClick={() => updateText('Updated!')}>Edit</button>
227 <button onClick={deleteTodo}>Delete</button>
228 </div>
229 )
230}
231```
232
233## Next Steps
234
235You now understand the basics of TanStack DB! The collection loads and persists data, live queries provide reactive views, and mutations give instant feedback with automatic server sync.
236
237Explore the docs to learn more about:
238
239- **[Installation](./installation.md)** - All framework and collection packages
240- **[Overview](./overview.md)** - Complete feature overview and examples
241- **[Live Queries](./guides/live-queries.md)** - Advanced querying, joins, and aggregations