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

overview.md

914 lines32.0 KB

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 )
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 })
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 })
222```
223​
224The Electric collection requires two Electric-specific options:
225​
226- `shapeOptions` &mdash; 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` &mdash; 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 })
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.
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 })
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 })
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 })
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 })
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 })
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 } />
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 } />
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, e.g.:
521​
522```tsx
523import type { MutationFn } from "@tanstack/react-db"
524​
525const mutationFn: MutationFn = async ({ transaction }) => {
526 const response = await api.todos.create(transaction.mutations)
527​
528 if (!response.ok) {
529 // Throwing an error will rollback the optimistic state.
530 throw new Error(`HTTP Error: ${response.status}`)
531 }
532​
533 const result = await response.json()
534​
535 // Wait for the transaction to be synced back from the server
536 // before discarding the optimistic state.
537 const collection: Collection = transaction.mutations[0].collection
538 await collection.refetch()
540```
541​
542#### `createOptimisticAction`
543​
544Use `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:
545​
546```tsx
547import { createOptimisticAction } from "@tanstack/react-db"
548​
549// Create the `addTodo` action, passing in your `mutationFn` and `onMutate`.
550const addTodo = createOptimisticAction<string>({
551 onMutate: (text) => {
552 // Instantly applies the local optimistic state.
553 todoCollection.insert({
554 id: uuid(),
555 text,
556 completed: false,
557 })
558 },
559 mutationFn: async (text) => {
560 // Persist the todo to your backend
561 const response = await fetch("/api/todos", {
562 method: "POST",
563 body: JSON.stringify({ text, completed: false }),
564 })
565 return response.json()
566 },
567})
568​
569const Todo = () => {
570 const handleClick = () => {
571 // Triggers the onMutate and then the mutationFn
572 addTodo("🔥 Make app faster")
573 }
574​
575 return <Button onClick={handleClick} />
577```
578​
579## Manual Transactions
580​
581By manually creating transactions, you can fully control their lifecycles and behaviors. `createOptimisticAction` is a ~25 line
582function which implements a common transaction pattern. Feel free to invent your own patterns!
583​
584Here's one way you could use transactions.
585​
586```ts
587import { createTransaction } from "@tanstack/react-db"
588​
589const addTodoTx = createTransaction({
590 autoCommit: false,
591 mutationFn: async ({ transaction }) => {
592 // Persist data to backend
593 await Promise.all(transaction.mutations.map(mutation => {
594 return await api.saveTodo(mutation.modified)
595 })
596 },
597})
598​
599// Apply first change
600addTodoTx.mutate(() => todoCollection.insert({ id: '1', text: 'First todo', completed: false }))
601​
602// user reviews change
603​
604// Apply another change
605addTodoTx.mutate(() => todoCollection.insert({ id: '2', text: 'Second todo', completed: false }))
606​
607// User decides to save and we call .commit() and the mutations are persisted to the backend.
608addTodoTx.commit()
609```
610​
611## Transaction lifecycle
612​
613Transactions progress through the following states:
614​
6151. `pending`: Initial state when a transaction is created and optimistic mutations can be applied
6162. `persisting`: Transaction is being persisted to the backend
6173. `completed`: Transaction has been successfully persisted and any backend changes have been synced back.
6184. `failed`: An error was thrown while persisting or syncing back the Transaction
619​
620#### Write operations
621​
622Collections support `insert`, `update` and `delete` operations.
623​
624##### `insert`
625​
626```typescript
627// Insert a single item
628myCollection.insert({ text: "Buy groceries", completed: false })
629​
630// Insert multiple items
631insert([
632 { text: "Buy groceries", completed: false },
633 { text: "Walk dog", completed: false },
634])
635​
636// Insert with optimistic updates disabled
637myCollection.insert(
638 { text: "Server-validated item", completed: false },
639 { optimistic: false }
641​
642// Insert with metadata and optimistic control
643myCollection.insert(
644 { text: "Custom item", completed: false },
645 {
646 metadata: { source: "import" },
647 optimistic: true, // default behavior
648 }
650```
651​
652##### `update`
653​
654We use a proxy to capture updates as immutable draft optimistic updates.
655​
656```typescript
657// Update a single item
658update(todo.id, (draft) => {
659 draft.completed = true
660})
661​
662// Update multiple items
663update([todo1.id, todo2.id], (drafts) => {
664 drafts.forEach((draft) => {
665 draft.completed = true
666 })
667})
668​
669// Update with metadata
670update(todo.id, { metadata: { reason: "user update" } }, (draft) => {
671 draft.text = "Updated text"
672})
673​
674// Update without optimistic updates
675update(todo.id, { optimistic: false }, (draft) => {
676 draft.status = "server-validated"
677})
678​
679// Update with both metadata and optimistic control
680update(
681 todo.id,
682 {
683 metadata: { reason: "admin update" },
684 optimistic: false,
685 },
686 (draft) => {
687 draft.priority = "high"
688 }
690```
691​
692##### `delete`
693​
694```typescript
695// Delete a single item
696delete todo.id
697​
698// Delete multiple items
699delete [todo1.id, todo2.id]
700​
701// Delete with metadata
702delete (todo.id, { metadata: { reason: "completed" } })
703​
704// Delete without optimistic updates (waits for server confirmation)
705delete (todo.id, { optimistic: false })
706​
707// Delete with metadata and optimistic control
708delete (todo.id,
710 metadata: { reason: "admin deletion" },
711 optimistic: false,
712})
713```
714​
715#### Controlling optimistic behavior
716​
717By 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.
718​
719##### When to use `optimistic: false`
720​
721Consider disabling optimistic updates when:
722​
723- **Complex server-side processing**: Inserts that depend on server-side generation (e.g., cascading foreign keys, computed fields)
724- **Validation requirements**: Operations where backend validation might reject the change
725- **Confirmation workflows**: Deletes where UX should wait for confirmation before removing data
726- **Batch operations**: Large operations where optimistic rollback would be disruptive
727​
728##### Behavior differences
729​
730**`optimistic: true` (default)**:
731​
732- Immediately applies mutation to the local store
733- Provides instant UI feedback
734- Requires rollback if server rejects the mutation
735- Best for simple, predictable operations
736​
737**`optimistic: false`**:
738​
739- Does not modify local store until server confirms
740- No immediate UI feedback, but no rollback needed
741- UI updates only after successful server response
742- Best for complex or validation-heavy operations
743​
744```typescript
745// Example: Critical deletion that needs confirmation
746const handleDeleteAccount = () => {
747 // Don't remove from UI until server confirms
748 userCollection.delete(userId, { optimistic: false })
750​
751// Example: Server-generated data
752const handleCreateInvoice = () => {
753 // Server generates invoice number, tax calculations, etc.
754 invoiceCollection.insert(invoiceData, { optimistic: false })
756​
757// Example: Mixed approach in same transaction
758tx.mutate(() => {
759 // Instant UI feedback for simple change
760 todoCollection.update(todoId, (draft) => {
761 draft.completed = true
762 })
763​
764 // Wait for server confirmation for complex change
765 auditCollection.insert(auditRecord, { optimistic: false })
766})
767```
768​
769## Usage examples
770​
771Here we illustrate two common ways of using TanStack DB:
772​
7731. [using TanStack Query](#1-tanstack-query) with an existing REST API
7742. [using the ElectricSQL sync engine](#2-electricsql-sync) with a generic ingestion endpoint
775​
776> [!TIP]
777> 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.
778​
779### 1. TanStack Query
780​
781You can use TanStack DB with your existing REST API via TanStack Query.
782​
783The steps are to:
784​
7851. create [`QueryCollection`](#querycollection)s that load data using TanStack Query
7862. implement [`mutationFn`](#mutationfn)s that handle mutations by posting them to your API endpoints
787​
788```tsx
789import { useLiveQuery, createCollection } from "@tanstack/react-db"
790import { queryCollectionOptions } from "@tanstack/query-db-collection"
791​
792// Load data into collections using TanStack Query.
793// It's common to define these in a `collections` module.
794const todoCollection = createCollection(queryCollectionOptions({
795 queryKey: ["todos"],
796 queryFn: async () => fetch("/api/todos"),
797 getKey: (item) => item.id,
798 schema: todoSchema, // any standard schema
799 onInsert: async ({ transaction }) => {
800 const { changes: newTodo } = transaction.mutations[0]
801​
802 // Handle the local write by sending it to your API.
803 await api.todos.create(newTodo)
804 }
805 // also add onUpdate, onDelete as needed.
806}))
807const listCollection = createCollection(queryCollectionOptions({
808 queryKey: ["todo-lists"],
809 queryFn: async () => fetch("/api/todo-lists"),
810 getKey: (item) => item.id,
811 schema: todoListSchema,
812 onInsert: async ({ transaction }) => {
813 const { changes: newTodo } = transaction.mutations[0]
814​
815 // Handle the local write by sending it to your API.
816 await api.todoLists.create(newTodo)
817 }
818 // also add onUpdate, onDelete as needed.
819}))
820​
821const Todos = () => {
822 // Read the data using live queries. Here we show a live
823 // query that joins across two collections.
824 const { data: todos } = useLiveQuery((q) =>
825 q
826 .from({ todo: todoCollection })
827 .join(
828 { list: listCollection },
829 ({ todo, list }) => eq(list.id, todo.list_id),
830 'inner'
831 )
832 .where(({ list }) => eq(list.active, true))
833 .select(({ todo, list }) => ({
834 id: todo.id,
835 text: todo.text,
836 status: todo.status,
837 listName: list.name
838 }))
839 )
840​
841 // ...
842​
844```
845​
846This 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.
847​
848### 2. ElectricSQL sync
849​
850One 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.
851​
852Here, we illustrate this pattern using [ElectricSQL](https://electric-sql.com) as the sync engine.
853​
854```tsx
855import type { Collection } from '@tanstack/db'
856import type { MutationFn, PendingMutation, createCollection } from '@tanstack/react-db'
857import { electricCollectionOptions } from '@tanstack/electric-db-collection'
858​
859export const todoCollection = createCollection(electricCollectionOptions({
860 id: 'todos',
861 schema: todoSchema,
862 // Electric syncs data using "shapes". These are filtered views
863 // on database tables that Electric keeps in sync for you.
864 shapeOptions: {
865 url: 'https://api.electric-sql.cloud/v1/shape',
866 params: {
867 table: 'todos'
868 }
869 },
870 getKey: (item) => item.id,
871 schema: todoSchema,
872 onInsert: async ({ transaction }) => {
873 const response = await api.todos.create(transaction.mutations[0].modified)
874​
875 return { txid: response.txid}
876 }
877 // You can also implement onUpdate, onDelete as needed.
878}))
879​
880const AddTodo = () => {
881 return (
882 <Button
883 onClick={() =>
884 todoCollection.insert({ text: "🔥 Make app faster" })
885 }
886 />
887 )
889```
890​
891## React Native
892​
893When 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.
894​
895Install the `react-native-random-uuid` package:
896​
897```bash
898npm install react-native-random-uuid
899```
900​
901Then import it at the entry point of your React Native app (e.g., in your `App.js` or `index.js`):
902​
903```javascript
904import 'react-native-random-uuid'
905```
906​
907This polyfill provides the `crypto.randomUUID()` function that TanStack DB uses internally for generating unique identifiers.
908​
909## More info
910​
911If you have questions / need help using TanStack DB, let us know on the Discord or start a GitHub discussion:
912​
913- [`#db` channel in the TanStack discord](https://discord.gg/yjUNbvbraC)
914- [GitHub discussions](https://github.com/tanstack/db/discussions)