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

quick-start.md

237 lines6.8 KB

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