Open History to see the last commit
1---
2title: Overview
3id: overview
4---
5
6# TanStack DB - Documentation
7
8Welcome to the TanStack DB documentation.
9
10TanStack DB is a reactive client store for building super fast apps on sync. It extends TanStack Query with collections, live queries and optimistic mutations.
11
12## Contents
13
14- [How it works](#how-it-works) — understand the TanStack DB development model and how the pieces fit together
15- [API reference](#api-reference) — for the primitives and function interfaces
16- [Usage examples](#usage-examples) — examples of common usage patterns
17- [More info](#more-info) — where to find support and more information
18
19## How it works
20
21TanStack DB works by:
22
23- [defining collections](#defining-collections) typed sets of objects that can be populated with data
24- [using live queries](#using-live-queries) to query data from/across collections
25- [making optimistic mutations](#making-optimistic-mutations) using transactional mutators
26
27```tsx
28// Define collections to load data into
29const todoCollection = createCollection({
30 // ...your config
31 onUpdate: updateMutationFn,
32})
33
34const Todos = () => {
35 // Bind data using live queries
36 const { data: todos } = useLiveQuery((q) =>
37 q.from({ todo: todoCollection }).where(({ todo }) => todo.completed)
38 )
39
40 const complete = (todo) => {
41 // Instantly applies optimistic state
42 todoCollection.update(todo.id, (draft) => {
43 draft.completed = true
44 })
45 }
46
47 return (
48 <ul>
49 {todos.map((todo) => (
50 <li key={todo.id} onClick={() => complete(todo)}>
51 {todo.text}
52 </li>
53 ))}
54 </ul>
55 )
56}
57```
58
59### Defining collections
60
61Collections are typed sets of objects that can be populated with data. They're designed to de-couple loading data into your app from binding data to your components.
62
63Collections can be populated in many ways, including:
64
65- fetching data, for example [from API endpoints using TanStack Query](https://tanstack.com/query/latest)
66- syncing data, for example [using a sync engine like ElectricSQL](https://electric-sql.com/)
67- storing local data, for example [using localStorage for user preferences and settings](#localstoragecollection) or [in-memory client data or UI state](#localonlycollection)
68- from live collection queries, creating [derived collections as materialised views](#using-live-queries)
69
70Once you have your data in collections, you can query across them using live queries in your components.
71
72### Using live queries
73
74Live queries are used to query data out of collections. Live queries are reactive: when the underlying data changes in a way that would affect the query result, the result is incrementally updated and returned from the query, triggering a re-render.
75
76TanStack DB live queries are implemented using [d2ts](https://github.com/electric-sql/d2ts), a Typescript implementation of differential dataflow. This allows the query results to update _incrementally_ (rather than by re-running the whole query). This makes them blazing fast, usually sub-millisecond, even for highly complex queries.
77
78Live queries support joins across collections. This allows you to:
79
801. load normalised data into collections and then de-normalise it through queries; simplifying your backend by avoiding the need for bespoke API endpoints that match your client
812. join data from multiple sources; for example, syncing some data out of a database, fetching some other data from an external API and then joining these into a unified data model for your front-end code
82
83Every query returns another collection which can _also_ be queried.
84
85For more details on live queries, see the [Live Queries](../guides/live-queries.md) documentation.
86
87### Making optimistic mutations
88
89Collections support `insert`, `update` and `delete` operations. When called, by default they trigger the corresponding `onInsert`, `onUpdate`, `onDelete` handlers which are responsible for writing the mutation to the backend.
90
91```ts
92// Define collection with persistence handlers
93const todoCollection = createCollection({
94 id: "todos",
95 // ... other config
96 onUpdate: async ({ transaction }) => {
97 const { original, changes } = transaction.mutations[0]
98 await api.todos.update(original.id, changes)
99 },
100})
101
102// Immediately applies optimistic state
103todoCollection.update(todo.id, (draft) => {
104 draft.completed = true
105})
106```
107
108Rather than mutating the collection data directly, the collection internally treats its synced/loaded data as immutable and maintains a separate set of local mutations as optimistic state. When live queries read from the collection, they see a local view that overlays the local optimistic mutations on-top-of the immutable synced data.
109
110The optimistic state is held until the `onUpdate` (in this case) handler resolves - at which point the data is persisted to the server and synced back to the local collection.
111
112If the handler throws an error, the optimistic state is rolled back.
113
114### Explicit transactions
115
116Mutations are based on a `Transaction` primitive.
117
118For simple state changes, directly mutating the collection and persisting with the operator handlers is enough.
119
120But for more complex use cases, you can directly create custom actions with `createOptimisticAction` or custom transactions with `createTransaction`. This lets you do things such as do transactions with multiple mutations across multiple collections, do chained transactions w/ intermediate rollbacks, etc.
121
122For example, in the following code, the mutationFn first sends the write to the server using `await api.todos.update(updatedTodo)` and then calls `await collection.refetch()` to trigger a re-fetch of the collection contents using TanStack Query. When this second await resolves, the collection is up-to-date with the latest changes and the optimistic state is safely discarded.
123
124```ts
125const updateTodo = createOptimisticAction<{ id: string }>({
126 onMutate,
127 mutationFn: async ({ transaction }) => {
128 const { collection, modified: updatedTodo } = transaction.mutations[0]
129
130 await api.todos.update(updatedTodo)
131 await collection.refetch()
132 },
133})
134```
135
136### Uni-directional data flow
137
138This combines to support a model of uni-directional data flow, extending the redux/flux style state management pattern beyond the client, to take in the server as well:
139
140<figure>
141 <a href="./unidirectional-data-flow.lg.png" target="_blank">
142 <img src="./unidirectional-data-flow.png" />
143 </a>
144</figure>
145
146With an instant inner loop of optimistic state, superseded in time by the slower outer loop of persisting to the server and syncing the updated server state back into the collection.
147
148## API reference
149
150### Collections
151
152There are a number of built-in collection types:
153
1541. [`QueryCollection`](#querycollection) to load data into collections using [TanStack Query](https://tanstack.com/query)
1552. [`ElectricCollection`](#electriccollection) to sync data into collections using [ElectricSQL](https://electric-sql.com)
1563. [`TrailBaseCollection`](#trailbasecollection) to sync data into collections using [TrailBase](https://trailbase.io)
1574. [`LocalStorageCollection`](#localstoragecollection) for small amounts of local-only state that syncs across browser tabs
1585. [`LocalOnlyCollection`](#localonlycollection) for in-memory client data or UI state
159
160You can also use:
161
162- use live collection queries to [derive collections from other collections](#derived-collections)
163- the [base Collection](#base-collection) to define your own collection types
164
165#### Collection schemas
166
167All collections optionally (though strongly recommended) support adding a `schema`.
168
169If provided, this must be a [Standard Schema](https://standardschema.dev) compatible schema instance, such as a [Zod](https://zod.dev) or [Effect](https://effect.website/docs/schema/introduction/) schema.
170
171The collection will use the schema to do client-side validation of optimistic mutations.
172
173The collection will use the schema for its type so if you provide a schema, you can't also pass in an explicit
174type (e.g. `createCollection<Todo>()`).
175
176#### `QueryCollection`
177
178[TanStack Query](https://tanstack.com/query) fetches data using managed queries. Use `queryCollectionOptions` to fetch data into a collection using TanStack Query:
179
180```ts
181import { createCollection } from "@tanstack/react-db"
182import { queryCollectionOptions } from "@tanstack/query-db-collection"
183
184const todoCollection = createCollection(
185 queryCollectionOptions({
186 queryKey: ["todoItems"],
187 queryFn: async () => {
188 const response = await fetch("/api/todos");
189 return response.json();
190 },
191 getKey: (item) => item.id,
192 schema: todoSchema, // any standard schema
193 })
194)
195```
196
197The collection will be populated with the query results.
198
199#### `ElectricCollection`
200
201[Electric](https://electric-sql.com) is a read-path sync engine for Postgres. It allows you to sync subsets of data out of a Postgres database, [through your API](https://electric-sql.com/blog/2024/11/21/local-first-with-your-existing-api), into a TanStack DB collection.
202
203Electric's main primitive for sync is a [Shape](https://electric-sql.com/docs/guides/shapes). Use `electricCollectionOptions` to sync a shape into a collection:
204
205```ts
206import { createCollection } from "@tanstack/react-db"
207import { electricCollectionOptions } from "@tanstack/electric-db-collection"
208
209export const todoCollection = createCollection(
210 electricCollectionOptions({
211 id: "todos",
212 shapeOptions: {
213 url: "https://example.com/v1/shape",
214 params: {
215 table: "todos",
216 },
217 },
218 getKey: (item) => item.id,
219 schema: todoSchema,
220 })
221)
222```
223
224The Electric collection requires two Electric-specific options:
225
226- `shapeOptions` — the Electric [ShapeStreamOptions](https://electric-sql.com/docs/api/clients/typescript#options) that define the [Shape](https://electric-sql.com/docs/guides/shapes) to sync into the collection; this includes the
227 - `url` to your sync engine; and
228 - `params` to specify the `table` to sync and any optional `where` clauses, etc.
229- `getKey` — identifies the id for the rows being synced into the collection
230
231A new collections doesn't start syncing until you call `collection.preload()` or you query it.
232
233Electric shapes allow you to filter data using where clauses:
234
235```ts
236export const myPendingTodos = createCollection(
237 electricCollectionOptions({
238 id: "todos",
239 shapeOptions: {
240 url: "https://example.com/v1/shape",
241 params: {
242 table: "todos",
243 where: `
244 status = 'pending'
245 AND
246 user_id = '${user.id}'
247 `,
248 },
249 },
250 getKey: (item) => item.id,
251 schema: todoSchema,
252 })
253)
254```
255
256> [!TIP]
257> Shape where clauses, used to filter the data you sync into `ElectricCollection`s, are different from the [live queries](#live-queries) you use to query data in components.
258>
259> Live queries are much more expressive than shapes, allowing you to query across collections, join, aggregate, etc. Shapes just contain filtered database tables and are used to populate the data in a collection.
260
261If you need more control over what data syncs into the collection, Electric allows you to [use your API](https://electric-sql.com/blog/2024/11/21/local-first-with-your-existing-api#filtering) as a proxy to both authorize and filter data.
262
263See the [Electric docs](https://electric-sql.com/docs/intro) for more information.
264
265#### `TrailBaseCollection`
266
267[TrailBase](https://trailbase.io) is an easy-to-self-host, single-executable application backend with built-in SQLite, a V8 JS runtime, auth, admin UIs and sync functionality.
268
269TrailBase lets you expose tables via [Record APIs](https://trailbase.io/documentation/apis_record/) and subscribe to changes when `enable_subscriptions` is set. Use `trailBaseCollectionOptions` to sync records into a collection:
270
271```ts
272import { createCollection } from "@tanstack/react-db"
273import { trailBaseCollectionOptions } from "@tanstack/trailbase-db-collection"
274import { initClient } from "trailbase"
275
276const trailBaseClient = initClient(`https://trailbase.io`)
277
278export const todoCollection = createCollection<SelectTodo, Todo>(
279 electricCollectionOptions({
280 id: "todos",
281 recordApi: trailBaseClient.records(`todos`),
282 getKey: (item) => item.id,
283 schema: todoSchema,
284 parse: {
285 created_at: (ts) => new Date(ts * 1000),
286 },
287 serialize: {
288 created_at: (date) => Math.floor(date.valueOf() / 1000),
289 },
290 })
291)
292```
293
294This collection requires the following TrailBase-specific options:
295
296- `recordApi` — identifies the API to sync.
297- `getKey` — identifies the id for the records being synced into the collection.
298- `parse` — maps `(v: Todo[k]) => SelectTodo[k]`.
299- `serialize` — maps `(v: SelectTodo[k]) => Todo[k]`.
300
301A new collections doesn't start syncing until you call `collection.preload()` or you query it.
302
303
304#### `LocalStorageCollection`
305
306localStorage collections store small amounts of local-only state that persists across browser sessions and syncs across browser tabs in real-time. All data is stored under a single localStorage key and automatically synchronized using storage events.
307
308Use `localStorageCollectionOptions` to create a collection that stores data in localStorage:
309
310```ts
311import { createCollection } from "@tanstack/react-db"
312import { localStorageCollectionOptions } from "@tanstack/react-db"
313
314export const userPreferencesCollection = createCollection(
315 localStorageCollectionOptions({
316 id: "user-preferences",
317 storageKey: "app-user-prefs", // localStorage key
318 getKey: (item) => item.id,
319 schema: userPrefsSchema,
320 })
321)
322```
323
324The localStorage collection requires:
325
326- `storageKey` — the localStorage key where all collection data is stored
327- `getKey` — identifies the id for items in the collection
328
329Mutation handlers (`onInsert`, `onUpdate`, `onDelete`) are completely optional. Data will persist to localStorage whether or not you provide handlers. You can provide alternative storage backends like `sessionStorage` or custom implementations that match the localStorage API.
330
331```ts
332export const sessionCollection = createCollection(
333 localStorageCollectionOptions({
334 id: "session-data",
335 storageKey: "session-key",
336 storage: sessionStorage, // Use sessionStorage instead
337 getKey: (item) => item.id,
338 })
339)
340```
341
342> [!TIP]
343> localStorage collections are perfect for user preferences, UI state, and other data that should persist locally but doesn't need server synchronization. For server-synchronized data, use [`QueryCollection`](#querycollection) or [`ElectricCollection`](#electriccollection) instead.
344
345#### `LocalOnlyCollection`
346
347LocalOnly collections are designed for in-memory client data or UI state that doesn't need to persist across browser sessions or sync across tabs. They provide a simple way to manage temporary, session-only data with full optimistic mutation support.
348
349Use `localOnlyCollectionOptions` to create a collection that stores data only in memory:
350
351```ts
352import { createCollection } from "@tanstack/react-db"
353import { localOnlyCollectionOptions } from "@tanstack/react-db"
354
355export const uiStateCollection = createCollection(
356 localOnlyCollectionOptions({
357 id: "ui-state",
358 getKey: (item) => item.id,
359 schema: uiStateSchema,
360 // Optional initial data to populate the collection
361 initialData: [
362 { id: "sidebar", isOpen: false },
363 { id: "theme", mode: "light" },
364 ],
365 })
366)
367```
368
369The LocalOnly collection requires:
370
371- `getKey` — identifies the id for items in the collection
372
373Optional configuration:
374
375- `initialData` — array of items to populate the collection with on creation
376- `onInsert`, `onUpdate`, `onDelete` — optional mutation handlers for custom logic
377
378Mutation handlers are completely optional. When provided, they are called before the optimistic state is confirmed. The collection automatically manages the transition from optimistic to confirmed state internally.
379
380```ts
381export const tempDataCollection = createCollection(
382 localOnlyCollectionOptions({
383 id: "temp-data",
384 getKey: (item) => item.id,
385 onInsert: async ({ transaction }) => {
386 // Custom logic before confirming the insert
387 console.log("Inserting:", transaction.mutations[0].modified)
388 },
389 onUpdate: async ({ transaction }) => {
390 // Custom logic before confirming the update
391 const { original, modified } = transaction.mutations[0]
392 console.log("Updating from", original, "to", modified)
393 },
394 })
395)
396```
397
398> [!TIP]
399> LocalOnly collections are perfect for temporary UI state, form data, or any client-side data that doesn't need persistence. For data that should persist across sessions, use [`LocalStorageCollection`](#localstoragecollection) instead.
400
401#### Derived collections
402
403Live queries return collections. This allows you to derive collections from other collections.
404
405For example:
406
407```ts
408import { createLiveQueryCollection, eq } from "@tanstack/db"
409
410// Imagine you have a collection of todos.
411const todoCollection = createCollection({
412 // config
413})
414
415// You can derive a new collection that's a subset of it.
416const completedTodoCollection = createLiveQueryCollection({
417 startSync: true,
418 query: (q) =>
419 q.from({ todo: todoCollection }).where(({ todo }) => todo.completed),
420})
421```
422
423This also works with joins to derive collections from multiple source collections. And it works recursively -- you can derive collections from other derived collections. Changes propagate efficiently using differential dataflow and it's collections all the way down.
424
425#### Collection
426
427There is a `Collection` interface in [`../packages/db/src/collection.ts`](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts). You can use this to implement your own collection types.
428
429See the existing implementations in [`../packages/db`](https://github.com/TanStack/db/tree/main/packages/db), [`../packages/query-db-collection`](https://github.com/TanStack/db/tree/main/packages/query-db-collection), [`../packages/electric-db-collection`](https://github.com/TanStack/db/tree/main/packages/electric-db-collection) and [`../packages/trailbase-db-collection`](https://github.com/TanStack/db/tree/main/packages/trailbase-db-collection) for reference.
430
431### Live queries
432
433#### `useLiveQuery` hook
434
435Use the `useLiveQuery` hook to assign live query results to a state variable in your React components:
436
437```ts
438import { useLiveQuery } from '@tanstack/react-db'
439import { eq } from '@tanstack/db'
440
441const Todos = () => {
442 const { data: todos } = useLiveQuery((q) =>
443 q
444 .from({ todo: todoCollection })
445 .where(({ todo }) => eq(todo.completed, false))
446 .orderBy(({ todo }) => todo.created_at, 'asc')
447 .select(({ todo }) => ({
448 id: todo.id,
449 text: todo.text
450 }))
451 )
452
453 return <List items={ todos } />
454}
455```
456
457You can also query across collections with joins:
458
459```ts
460import { useLiveQuery } from '@tanstack/react-db'
461import { eq } from '@tanstack/db'
462
463const Todos = () => {
464 const { data: todos } = useLiveQuery((q) =>
465 q
466 .from({ todos: todoCollection })
467 .join(
468 { lists: listCollection },
469 ({ todos, lists }) => eq(lists.id, todos.listId),
470 'inner'
471 )
472 .where(({ lists }) => eq(lists.active, true))
473 .select(({ todos, lists }) => ({
474 id: todos.id,
475 title: todos.title,
476 listName: lists.name
477 }))
478 )
479
480 return <List items={ todos } />
481}
482```
483
484#### `queryBuilder`
485
486You can also build queries directly (outside of the component lifecycle) using the underlying `queryBuilder` API:
487
488```ts
489import { createLiveQueryCollection, eq } from "@tanstack/db"
490
491const completedTodos = createLiveQueryCollection({
492 startSync: true,
493 query: (q) =>
494 q
495 .from({ todo: todoCollection })
496 .where(({ todo }) => eq(todo.completed, true)),
497})
498
499const results = completedTodos.toArray
500```
501
502Note also that:
503
5041. the query results [are themselves a collection](#derived-collections)
5052. the `useLiveQuery` automatically starts and stops live query subscriptions when you mount and unmount your components; if you're creating queries manually, you need to manually manage the subscription lifecycle yourself
506
507See the [Live Queries](../guides/live-queries.md) documentation for more details.
508
509### Transactional mutators
510
511Transactional mutators allow you to batch and stage local changes across collections with:
512
513- immediate application of local optimistic updates
514- flexible mutationFns to handle writes, with automatic rollbacks and management of optimistic state
515
516#### `mutationFn`
517
518Mutators are created with a `mutationFn`. You can define a single, generic `mutationFn` for your whole app. Or you can define collection or mutation specific functions.
519
520The `mutationFn` is responsible for handling the local changes and processing them, usually to send them to a server or database to be stored.
521
522**Important:** Inside your `mutationFn`, you must ensure that your server writes have synced back before you return, as the optimistic state is dropped when you return from the mutation function. You generally use collection-specific helpers to do this, such as Query's `utils.refetch()`, direct write APIs, or Electric's `utils.awaitTxId()`.
523
524For example:
525
526```tsx
527import type { MutationFn } from "@tanstack/react-db"
528
529const mutationFn: MutationFn = async ({ transaction }) => {
530 const response = await api.todos.create(transaction.mutations)
531
532 if (!response.ok) {
533 // Throwing an error will rollback the optimistic state.
534 throw new Error(`HTTP Error: ${response.status}`)
535 }
536
537 const result = await response.json()
538
539 // Wait for the transaction to be synced back from the server
540 // before discarding the optimistic state.
541 const collection: Collection = transaction.mutations[0].collection
542 await collection.refetch()
543}
544```
545
546#### `createOptimisticAction`
547
548Use `createOptimisticAction` with your `mutationFn` and `onMutate` functions to create an action that you can use to mutate data in your components in fully custom ways:
549
550```tsx
551import { createOptimisticAction } from "@tanstack/react-db"
552
553// Create the `addTodo` action, passing in your `mutationFn` and `onMutate`.
554const addTodo = createOptimisticAction<string>({
555 onMutate: (text) => {
556 // Instantly applies the local optimistic state.
557 todoCollection.insert({
558 id: uuid(),
559 text,
560 completed: false,
561 })
562 },
563 mutationFn: async (text, params) => {
564 // Persist the todo to your backend
565 const response = await fetch("/api/todos", {
566 method: "POST",
567 body: JSON.stringify({ text, completed: false }),
568 })
569 const result = await response.json()
571 // IMPORTANT: Ensure server writes have synced back before returning
572 // This ensures the optimistic state can be safely discarded
573 await todoCollection.utils.refetch()
575 return result
576 },
577})
578
579const Todo = () => {
580 const handleClick = () => {
581 // Triggers the onMutate and then the mutationFn
582 addTodo("🔥 Make app faster")
583 }
584
585 return <Button onClick={handleClick} />
586}
587```
588
589## Manual Transactions
590
591By manually creating transactions, you can fully control their lifecycles and behaviors. `createOptimisticAction` is a ~25 line
592function which implements a common transaction pattern. Feel free to invent your own patterns!
593
594Here's one way you could use transactions.
595
596```ts
597import { createTransaction } from "@tanstack/react-db"
598
599const addTodoTx = createTransaction({
600 autoCommit: false,
601 mutationFn: async ({ transaction }) => {
602 // Persist data to backend
603 await Promise.all(transaction.mutations.map(mutation => {
604 return await api.saveTodo(mutation.modified)
605 })
606 },
607})
608
609// Apply first change
610addTodoTx.mutate(() => todoCollection.insert({ id: '1', text: 'First todo', completed: false }))
611
612// user reviews change
613
614// Apply another change
615addTodoTx.mutate(() => todoCollection.insert({ id: '2', text: 'Second todo', completed: false }))
616
617// User decides to save and we call .commit() and the mutations are persisted to the backend.
618addTodoTx.commit()
619```
620
621## Transaction lifecycle
622
623Transactions progress through the following states:
624
6251. `pending`: Initial state when a transaction is created and optimistic mutations can be applied
6262. `persisting`: Transaction is being persisted to the backend
6273. `completed`: Transaction has been successfully persisted and any backend changes have been synced back.
6284. `failed`: An error was thrown while persisting or syncing back the Transaction
629
630#### Write operations
631
632Collections support `insert`, `update` and `delete` operations.
633
634##### `insert`
635
636```typescript
637// Insert a single item
638myCollection.insert({ text: "Buy groceries", completed: false })
639
640// Insert multiple items
641insert([
642 { text: "Buy groceries", completed: false },
643 { text: "Walk dog", completed: false },
644])
645
646// Insert with optimistic updates disabled
647myCollection.insert(
648 { text: "Server-validated item", completed: false },
649 { optimistic: false }
650)
651
652// Insert with metadata and optimistic control
653myCollection.insert(
654 { text: "Custom item", completed: false },
655 {
656 metadata: { source: "import" },
657 optimistic: true, // default behavior
658 }
659)
660```
661
662##### `update`
663
664We use a proxy to capture updates as immutable draft optimistic updates.
665
666```typescript
667// Update a single item
668update(todo.id, (draft) => {
669 draft.completed = true
670})
671
672// Update multiple items
673update([todo1.id, todo2.id], (drafts) => {
674 drafts.forEach((draft) => {
675 draft.completed = true
676 })
677})
678
679// Update with metadata
680update(todo.id, { metadata: { reason: "user update" } }, (draft) => {
681 draft.text = "Updated text"
682})
683
684// Update without optimistic updates
685update(todo.id, { optimistic: false }, (draft) => {
686 draft.status = "server-validated"
687})
688
689// Update with both metadata and optimistic control
690update(
691 todo.id,
692 {
693 metadata: { reason: "admin update" },
694 optimistic: false,
695 },
696 (draft) => {
697 draft.priority = "high"
698 }
699)
700```
701
702##### `delete`
703
704```typescript
705// Delete a single item
706delete todo.id
707
708// Delete multiple items
709delete [todo1.id, todo2.id]
710
711// Delete with metadata
712delete (todo.id, { metadata: { reason: "completed" } })
713
714// Delete without optimistic updates (waits for server confirmation)
715delete (todo.id, { optimistic: false })
716
717// Delete with metadata and optimistic control
718delete (todo.id,
719{
720 metadata: { reason: "admin deletion" },
721 optimistic: false,
722})
723```
724
725#### Controlling optimistic behavior
726
727By default, all mutations (`insert`, `update`, `delete`) apply optimistic updates immediately to provide instant feedback in your UI. However, there are cases where you may want to disable this behavior and wait for server confirmation before applying changes locally.
728
729##### When to use `optimistic: false`
730
731Consider disabling optimistic updates when:
732
733- **Complex server-side processing**: Inserts that depend on server-side generation (e.g., cascading foreign keys, computed fields)
734- **Validation requirements**: Operations where backend validation might reject the change
735- **Confirmation workflows**: Deletes where UX should wait for confirmation before removing data
736- **Batch operations**: Large operations where optimistic rollback would be disruptive
737
738##### Behavior differences
739
740**`optimistic: true` (default)**:
741
742- Immediately applies mutation to the local store
743- Provides instant UI feedback
744- Requires rollback if server rejects the mutation
745- Best for simple, predictable operations
746
747**`optimistic: false`**:
748
749- Does not modify local store until server confirms
750- No immediate UI feedback, but no rollback needed
751- UI updates only after successful server response
752- Best for complex or validation-heavy operations
753
754```typescript
755// Example: Critical deletion that needs confirmation
756const handleDeleteAccount = () => {
757 // Don't remove from UI until server confirms
758 userCollection.delete(userId, { optimistic: false })
759}
760
761// Example: Server-generated data
762const handleCreateInvoice = () => {
763 // Server generates invoice number, tax calculations, etc.
764 invoiceCollection.insert(invoiceData, { optimistic: false })
765}
766
767// Example: Mixed approach in same transaction
768tx.mutate(() => {
769 // Instant UI feedback for simple change
770 todoCollection.update(todoId, (draft) => {
771 draft.completed = true
772 })
773
774 // Wait for server confirmation for complex change
775 auditCollection.insert(auditRecord, { optimistic: false })
776})
777```
778
779## Usage examples
780
781Here we illustrate two common ways of using TanStack DB:
782
7831. [using TanStack Query](#1-tanstack-query) with an existing REST API
7842. [using the ElectricSQL sync engine](#2-electricsql-sync) with a generic ingestion endpoint
785
786> [!TIP]
787> You can combine these patterns. One of the benefits of TanStack DB is that you can integrate different ways of loading data and handling mutations into the same app. Your components don't need to know where the data came from or goes.
788
789### 1. TanStack Query
790
791You can use TanStack DB with your existing REST API via TanStack Query.
792
793The steps are to:
794
7951. create [`QueryCollection`](#querycollection)s that load data using TanStack Query
7962. implement [`mutationFn`](#mutationfn)s that handle mutations by posting them to your API endpoints
797
798```tsx
799import { useLiveQuery, createCollection } from "@tanstack/react-db"
800import { queryCollectionOptions } from "@tanstack/query-db-collection"
801
802// Load data into collections using TanStack Query.
803// It's common to define these in a `collections` module.
804const todoCollection = createCollection(queryCollectionOptions({
805 queryKey: ["todos"],
806 queryFn: async () => fetch("/api/todos"),
807 getKey: (item) => item.id,
808 schema: todoSchema, // any standard schema
809 onInsert: async ({ transaction }) => {
810 const { changes: newTodo } = transaction.mutations[0]
811
812 // Handle the local write by sending it to your API.
813 await api.todos.create(newTodo)
814 }
815 // also add onUpdate, onDelete as needed.
816}))
817const listCollection = createCollection(queryCollectionOptions({
818 queryKey: ["todo-lists"],
819 queryFn: async () => fetch("/api/todo-lists"),
820 getKey: (item) => item.id,
821 schema: todoListSchema,
822 onInsert: async ({ transaction }) => {
823 const { changes: newTodo } = transaction.mutations[0]
824
825 // Handle the local write by sending it to your API.
826 await api.todoLists.create(newTodo)
827 }
828 // also add onUpdate, onDelete as needed.
829}))
830
831const Todos = () => {
832 // Read the data using live queries. Here we show a live
833 // query that joins across two collections.
834 const { data: todos } = useLiveQuery((q) =>
835 q
836 .from({ todo: todoCollection })
837 .join(
838 { list: listCollection },
839 ({ todo, list }) => eq(list.id, todo.list_id),
840 'inner'
841 )
842 .where(({ list }) => eq(list.active, true))
843 .select(({ todo, list }) => ({
844 id: todo.id,
845 text: todo.text,
846 status: todo.status,
847 listName: list.name
848 }))
849 )
850
851 // ...
852
853}
854```
855
856This pattern allows you to extend an existing TanStack Query application, or any application built on a REST API, with blazing fast, cross-collection live queries and local optimistic mutations with automatically managed optimistic state.
857
858### 2. ElectricSQL sync
859
860One of the most powerful ways of using TanStack DB is with a sync engine, for a fully local-first experience with real-time sync. This allows you to incrementally adopt sync into an existing app, whilst still handling writes with your existing API.
861
862Here, we illustrate this pattern using [ElectricSQL](https://electric-sql.com) as the sync engine.
863
864```tsx
865import type { Collection } from '@tanstack/db'
866import type { MutationFn, PendingMutation, createCollection } from '@tanstack/react-db'
867import { electricCollectionOptions } from '@tanstack/electric-db-collection'
868
869export const todoCollection = createCollection(electricCollectionOptions({
870 id: 'todos',
871 schema: todoSchema,
872 // Electric syncs data using "shapes". These are filtered views
873 // on database tables that Electric keeps in sync for you.
874 shapeOptions: {
875 url: 'https://api.electric-sql.cloud/v1/shape',
876 params: {
877 table: 'todos'
878 }
879 },
880 getKey: (item) => item.id,
881 schema: todoSchema,
882 onInsert: async ({ transaction }) => {
883 const response = await api.todos.create(transaction.mutations[0].modified)
884
885 return { txid: response.txid}
886 }
887 // You can also implement onUpdate, onDelete as needed.
888}))
889
890const AddTodo = () => {
891 return (
892 <Button
893 onClick={() =>
894 todoCollection.insert({ text: "🔥 Make app faster" })
895 }
896 />
897 )
898}
899```
900
901## React Native
902
903When using TanStack DB with React Native, you need to install and configure a UUID generation library since React Native doesn't include crypto.randomUUID() by default.
904
905Install the `react-native-random-uuid` package:
906
907```bash
908npm install react-native-random-uuid
909```
910
911Then import it at the entry point of your React Native app (e.g., in your `App.js` or `index.js`):
912
913```javascript
914import 'react-native-random-uuid'
915```
916
917This polyfill provides the `crypto.randomUUID()` function that TanStack DB uses internally for generating unique identifiers.
918
919## More info
920
921If you have questions / need help using TanStack DB, let us know on the Discord or start a GitHub discussion:
922
923- [`#db` channel in the TanStack discord](https://discord.gg/yjUNbvbraC)
924- [GitHub discussions](https://github.com/tanstack/db/discussions)