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

overview.md

1,073 lines37.3 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="https://raw.githubusercontent.com/TanStack/db/main/docs/unidirectional-data-flow.lg.png" target="_blank">
142 <img src="https://raw.githubusercontent.com/TanStack/db/main/docs/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. [`RxDBCollection`](#rxdbcollection) to integrate with [RxDB](https://rxdb.info) for local persistence and sync
1585. [`LocalStorageCollection`](#localstoragecollection) for small amounts of local-only state that syncs across browser tabs
1596. [`LocalOnlyCollection`](#localonlycollection) for in-memory client data or UI state
160​
161You can also use:
162​
163- use live collection queries to [derive collections from other collections](#derived-collections)
164- the [base Collection](#base-collection) to define your own collection types
165​
166#### Collection schemas
167​
168All collections optionally (though strongly recommended) support adding a `schema`.
169​
170If 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.
171​
172The collection will use the schema to do client-side validation of optimistic mutations.
173​
174The collection will use the schema for its type so if you provide a schema, you can't also pass in an explicit
175type (e.g. `createCollection<Todo>()`).
176​
177#### `QueryCollection`
178​
179[TanStack Query](https://tanstack.com/query) fetches data using managed queries. Use `queryCollectionOptions` to fetch data into a collection using TanStack Query:
180​
181```ts
182import { createCollection } from "@tanstack/react-db"
183import { queryCollectionOptions } from "@tanstack/query-db-collection"
184​
185const todoCollection = createCollection(
186 queryCollectionOptions({
187 queryKey: ["todoItems"],
188 queryFn: async () => {
189 const response = await fetch("/api/todos")
190 return response.json()
191 },
192 getKey: (item) => item.id,
193 schema: todoSchema, // any standard schema
194 })
196```
197​
198The collection will be populated with the query results.
199​
200#### `ElectricCollection`
201​
202[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.
203​
204Electric's main primitive for sync is a [Shape](https://electric-sql.com/docs/guides/shapes). Use `electricCollectionOptions` to sync a shape into a collection:
205​
206```ts
207import { createCollection } from "@tanstack/react-db"
208import { electricCollectionOptions } from "@tanstack/electric-db-collection"
209​
210export const todoCollection = createCollection(
211 electricCollectionOptions({
212 id: "todos",
213 shapeOptions: {
214 url: "https://example.com/v1/shape",
215 params: {
216 table: "todos",
217 },
218 },
219 getKey: (item) => item.id,
220 schema: todoSchema,
221 })
223```
224​
225The Electric collection requires two Electric-specific options:
226​
227- `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
228 - `url` to your sync engine; and
229 - `params` to specify the `table` to sync and any optional `where` clauses, etc.
230- `getKey` &mdash; identifies the id for the rows being synced into the collection
231​
232A new collections doesn't start syncing until you call `collection.preload()` or you query it.
233​
234Electric shapes allow you to filter data using where clauses:
235​
236```ts
237export const myPendingTodos = createCollection(
238 electricCollectionOptions({
239 id: "todos",
240 shapeOptions: {
241 url: "https://example.com/v1/shape",
242 params: {
243 table: "todos",
244 where: `
245 status = 'pending'
246 AND
247 user_id = '${user.id}'
248 `,
249 },
250 },
251 getKey: (item) => item.id,
252 schema: todoSchema,
253 })
255```
256​
257> [!TIP]
258> 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.
260> 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.
261​
262If 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.
263​
264See the [Electric docs](https://electric-sql.com/docs/intro) for more information.
265​
266#### `TrailBaseCollection`
267​
268[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.
269​
270TrailBase 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:
271​
272```ts
273import { createCollection } from "@tanstack/react-db"
274import { trailBaseCollectionOptions } from "@tanstack/trailbase-db-collection"
275import { initClient } from "trailbase"
276​
277const trailBaseClient = initClient(`https://trailbase.io`)
278​
279export const todoCollection = createCollection<SelectTodo, Todo>(
280 trailBaseCollectionOptions({
281 id: "todos",
282 recordApi: trailBaseClient.records(`todos`),
283 getKey: (item) => item.id,
284 schema: todoSchema,
285 parse: {
286 created_at: (ts) => new Date(ts * 1000),
287 },
288 serialize: {
289 created_at: (date) => Math.floor(date.valueOf() / 1000),
290 },
291 })
293```
294​
295This collection requires the following TrailBase-specific options:
296​
297- `recordApi` — identifies the API to sync.
298- `getKey` — identifies the id for the records being synced into the collection.
299- `parse` — maps `(v: Todo[k]) => SelectTodo[k]`.
300- `serialize` — maps `(v: SelectTodo[k]) => Todo[k]`.
301​
302A new collections doesn't start syncing until you call `collection.preload()` or you query it.
303​
304#### `RxDBCollection`
305​
306[RxDB](https://rxdb.info) is a client-side database for JavaScript apps with replication, conflict resolution, and offline-first features.
307Use `rxdbCollectionOptions` from `@tanstack/rxdb-db-collection` to integrate an RxDB collection with TanStack DB:
308​
309```ts
310import { createCollection } from "@tanstack/react-db"
311import { rxdbCollectionOptions } from "@tanstack/rxdb-db-collection"
312import { createRxDatabase } from "rxdb"
313​
314const db = await createRxDatabase({
315 name: "mydb",
316 storage: getRxStorageMemory(),
317})
318await db.addCollections({
319 todos: {
320 schema: {
321 version: 0,
322 primaryKey: "id",
323 type: "object",
324 properties: {
325 id: { type: "string", maxLength: 100 },
326 text: { type: "string" },
327 completed: { type: "boolean" },
328 },
329 },
330 },
331})
332​
333// Wrap the RxDB collection with TanStack DB
334export const todoCollection = createCollection(
335 rxdbCollectionOptions({
336 rxCollection: db.todos,
337 startSync: true,
338 })
340```
341​
342With this integration:
343​
344- TanStack DB subscribes to RxDB's change streams and reflects updates, deletes, and inserts in real-time.
345- You get local-first sync when RxDB replication is configured.
346- Mutation handlers (onInsert, onUpdate, onDelete) are implemented using RxDB's APIs (bulkUpsert, incrementalPatch, bulkRemove).
347​
348This makes RxDB a great choice for apps that need local-first storage, replication, or peer-to-peer sync combined with TanStack DB's live queries and transaction lifecycle.
349​
350#### `LocalStorageCollection`
351​
352localStorage 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.
353​
354Use `localStorageCollectionOptions` to create a collection that stores data in localStorage:
355​
356```ts
357import { createCollection } from "@tanstack/react-db"
358import { localStorageCollectionOptions } from "@tanstack/react-db"
359​
360export const userPreferencesCollection = createCollection(
361 localStorageCollectionOptions({
362 id: "user-preferences",
363 storageKey: "app-user-prefs", // localStorage key
364 getKey: (item) => item.id,
365 schema: userPrefsSchema,
366 })
368```
369​
370The localStorage collection requires:
371​
372- `storageKey` — the localStorage key where all collection data is stored
373- `getKey` — identifies the id for items in the collection
374​
375Mutation 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.
376​
377```ts
378export const sessionCollection = createCollection(
379 localStorageCollectionOptions({
380 id: "session-data",
381 storageKey: "session-key",
382 storage: sessionStorage, // Use sessionStorage instead
383 getKey: (item) => item.id,
384 })
386```
387​
388> [!TIP]
389> 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.
390​
391#### `LocalOnlyCollection`
392​
393LocalOnly 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.
394​
395Use `localOnlyCollectionOptions` to create a collection that stores data only in memory:
396​
397```ts
398import { createCollection } from "@tanstack/react-db"
399import { localOnlyCollectionOptions } from "@tanstack/react-db"
400​
401export const uiStateCollection = createCollection(
402 localOnlyCollectionOptions({
403 id: "ui-state",
404 getKey: (item) => item.id,
405 schema: uiStateSchema,
406 // Optional initial data to populate the collection
407 initialData: [
408 { id: "sidebar", isOpen: false },
409 { id: "theme", mode: "light" },
410 ],
411 })
413```
414​
415The LocalOnly collection requires:
416​
417- `getKey` — identifies the id for items in the collection
418​
419Optional configuration:
420​
421- `initialData` — array of items to populate the collection with on creation
422- `onInsert`, `onUpdate`, `onDelete` — optional mutation handlers for custom logic
423​
424Mutation 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.
425​
426```ts
427export const tempDataCollection = createCollection(
428 localOnlyCollectionOptions({
429 id: "temp-data",
430 getKey: (item) => item.id,
431 onInsert: async ({ transaction }) => {
432 // Custom logic before confirming the insert
433 console.log("Inserting:", transaction.mutations[0].modified)
434 },
435 onUpdate: async ({ transaction }) => {
436 // Custom logic before confirming the update
437 const { original, modified } = transaction.mutations[0]
438 console.log("Updating from", original, "to", modified)
439 },
440 })
442```
443​
444> [!TIP]
445> 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.
446​
447#### Derived collections
448​
449Live queries return collections. This allows you to derive collections from other collections.
450​
451For example:
452​
453```ts
454import { createLiveQueryCollection, eq } from "@tanstack/db"
455​
456// Imagine you have a collection of todos.
457const todoCollection = createCollection({
458 // config
459})
460​
461// You can derive a new collection that's a subset of it.
462const completedTodoCollection = createLiveQueryCollection({
463 startSync: true,
464 query: (q) =>
465 q.from({ todo: todoCollection }).where(({ todo }) => todo.completed),
466})
467```
468​
469This 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.
470​
471#### Collection
472​
473There 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.
474​
475See 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.
476​
477### Live queries
478​
479#### `useLiveQuery` hook
480​
481Use the `useLiveQuery` hook to assign live query results to a state variable in your React components:
482​
483```ts
484import { useLiveQuery } from '@tanstack/react-db'
485import { eq } from '@tanstack/db'
486​
487const Todos = () => {
488 const { data: todos } = useLiveQuery((q) =>
489 q
490 .from({ todo: todoCollection })
491 .where(({ todo }) => eq(todo.completed, false))
492 .orderBy(({ todo }) => todo.created_at, 'asc')
493 .select(({ todo }) => ({
494 id: todo.id,
495 text: todo.text
496 }))
497 )
498​
499 return <List items={ todos } />
501```
502​
503You can also query across collections with joins:
504​
505```ts
506import { useLiveQuery } from '@tanstack/react-db'
507import { eq } from '@tanstack/db'
508​
509const Todos = () => {
510 const { data: todos } = useLiveQuery((q) =>
511 q
512 .from({ todos: todoCollection })
513 .join(
514 { lists: listCollection },
515 ({ todos, lists }) => eq(lists.id, todos.listId),
516 'inner'
517 )
518 .where(({ lists }) => eq(lists.active, true))
519 .select(({ todos, lists }) => ({
520 id: todos.id,
521 title: todos.title,
522 listName: lists.name
523 }))
524 )
525​
526 return <List items={ todos } />
528```
529​
530#### `queryBuilder`
531​
532You can also build queries directly (outside of the component lifecycle) using the underlying `queryBuilder` API:
533​
534```ts
535import { createLiveQueryCollection, eq } from "@tanstack/db"
536​
537const completedTodos = createLiveQueryCollection({
538 startSync: true,
539 query: (q) =>
540 q
541 .from({ todo: todoCollection })
542 .where(({ todo }) => eq(todo.completed, true)),
543})
544​
545const results = completedTodos.toArray
546```
547​
548Note also that:
549​
5501. the query results [are themselves a collection](#derived-collections)
5512. 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
552​
553See the [Live Queries](../guides/live-queries.md) documentation for more details.
554​
555### Transactional mutators
556​
557Transactional mutators allow you to batch and stage local changes across collections with:
558​
559- immediate application of local optimistic updates
560- flexible mutationFns to handle writes, with automatic rollbacks and management of optimistic state
561​
562#### `mutationFn`
563​
564Mutators 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.
565​
566The `mutationFn` is responsible for handling the local changes and processing them, usually to send them to a server or database to be stored.
567​
568**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()`.
569​
570For example:
571​
572```tsx
573import type { MutationFn } from "@tanstack/react-db"
574​
575const mutationFn: MutationFn = async ({ transaction }) => {
576 const response = await api.todos.create(transaction.mutations)
577​
578 if (!response.ok) {
579 // Throwing an error will rollback the optimistic state.
580 throw new Error(`HTTP Error: ${response.status}`)
581 }
582​
583 const result = await response.json()
584​
585 // Wait for the transaction to be synced back from the server
586 // before discarding the optimistic state.
587 const collection: Collection = transaction.mutations[0].collection
588 await collection.refetch()
590```
591​
592#### `createOptimisticAction`
593​
594Use `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:
595​
596```tsx
597import { createOptimisticAction } from "@tanstack/react-db"
598​
599// Create the `addTodo` action, passing in your `mutationFn` and `onMutate`.
600const addTodo = createOptimisticAction<string>({
601 onMutate: (text) => {
602 // Instantly applies the local optimistic state.
603 todoCollection.insert({
604 id: uuid(),
605 text,
606 completed: false,
607 })
608 },
609 mutationFn: async (text, params) => {
610 // Persist the todo to your backend
611 const response = await fetch("/api/todos", {
612 method: "POST",
613 body: JSON.stringify({ text, completed: false }),
614 })
615 const result = await response.json()
616​
617 // IMPORTANT: Ensure server writes have synced back before returning
618 // This ensures the optimistic state can be safely discarded
619 await todoCollection.utils.refetch()
620​
621 return result
622 },
623})
624​
625const Todo = () => {
626 const handleClick = () => {
627 // Triggers the onMutate and then the mutationFn
628 addTodo("🔥 Make app faster")
629 }
630​
631 return <Button onClick={handleClick} />
633```
634​
635## Manual Transactions
636​
637By manually creating transactions, you can fully control their lifecycles and behaviors. `createOptimisticAction` is a ~25 line
638function which implements a common transaction pattern. Feel free to invent your own patterns!
639​
640Here's one way you could use transactions.
641​
642```ts
643import { createTransaction } from "@tanstack/react-db"
644​
645const addTodoTx = createTransaction({
646 autoCommit: false,
647 mutationFn: async ({ transaction }) => {
648 // Persist data to backend
649 await Promise.all(transaction.mutations.map(mutation => {
650 return await api.saveTodo(mutation.modified)
651 })
652 },
653})
654​
655// Apply first change
656addTodoTx.mutate(() => todoCollection.insert({ id: '1', text: 'First todo', completed: false }))
657​
658// user reviews change
659​
660// Apply another change
661addTodoTx.mutate(() => todoCollection.insert({ id: '2', text: 'Second todo', completed: false }))
662​
663// User decides to save and we call .commit() and the mutations are persisted to the backend.
664addTodoTx.commit()
665```
666​
667### Mutation Merging
668​
669When multiple mutations operate on the same item within a transaction, TanStack DB intelligently merges them to reduce over-the-wire churn and keep the optimistic local view aligned with user intent.
670​
671The merging behavior follows a truth table based on the mutation types:
672​
673| Existing → New | Result | Description |
674| ------------------- | --------- | ------------------------------------------------- |
675| **insert + update** | `insert` | Keeps insert type, merges changes, empty original |
676| **insert + delete** | _removed_ | Mutations cancel each other out |
677| **update + delete** | `delete` | Delete dominates |
678| **update + update** | `update` | Union changes, keep first original |
679| **same type** | _latest_ | Replace with most recent mutation |
680​
681#### Examples
682​
683**Insert followed by update:**
684​
685```ts
686const tx = createTransaction({ autoCommit: false, mutationFn })
687​
688// Insert a new todo
689tx.mutate(() =>
690 todoCollection.insert({
691 id: "1",
692 text: "Buy groceries",
693 completed: false,
694 })
696​
697// Update the same todo
698tx.mutate(() =>
699 todoCollection.update("1", (draft) => {
700 draft.text = "Buy organic groceries"
701 draft.priority = "high"
702 })
704​
705// Result: Single insert mutation with merged data
706// { id: '1', text: 'Buy organic groceries', completed: false, priority: 'high' }
707```
708​
709**Insert followed by delete:**
710​
711```ts
712// Insert then delete cancels out - no mutations sent to server
713tx.mutate(() => todoCollection.insert({ id: "1", text: "Temp todo" }))
714tx.mutate(() => todoCollection.delete("1"))
715​
716// Result: No mutations (they cancel each other out)
717```
718​
719This intelligent merging ensures that:
720​
721- **Network efficiency**: Fewer mutations sent to the server
722- **User intent preservation**: Final state matches what user expects
723- **Optimistic UI consistency**: Local state always reflects user actions
724​
725## Transaction lifecycle
726​
727Transactions progress through the following states:
728​
7291. `pending`: Initial state when a transaction is created and optimistic mutations can be applied
7302. `persisting`: Transaction is being persisted to the backend
7313. `completed`: Transaction has been successfully persisted and any backend changes have been synced back.
7324. `failed`: An error was thrown while persisting or syncing back the Transaction
733​
734#### Write operations
735​
736Collections support `insert`, `update` and `delete` operations.
737​
738##### `insert`
739​
740```typescript
741// Insert a single item
742myCollection.insert({ text: "Buy groceries", completed: false })
743​
744// Insert multiple items
745insert([
746 { text: "Buy groceries", completed: false },
747 { text: "Walk dog", completed: false },
748])
749​
750// Insert with optimistic updates disabled
751myCollection.insert(
752 { text: "Server-validated item", completed: false },
753 { optimistic: false }
755​
756// Insert with metadata and optimistic control
757myCollection.insert(
758 { text: "Custom item", completed: false },
759 {
760 metadata: { source: "import" },
761 optimistic: true, // default behavior
762 }
764```
765​
766##### `update`
767​
768We use a proxy to capture updates as immutable draft optimistic updates.
769​
770```typescript
771// Update a single item
772update(todo.id, (draft) => {
773 draft.completed = true
774})
775​
776// Update multiple items
777update([todo1.id, todo2.id], (drafts) => {
778 drafts.forEach((draft) => {
779 draft.completed = true
780 })
781})
782​
783// Update with metadata
784update(todo.id, { metadata: { reason: "user update" } }, (draft) => {
785 draft.text = "Updated text"
786})
787​
788// Update without optimistic updates
789update(todo.id, { optimistic: false }, (draft) => {
790 draft.status = "server-validated"
791})
792​
793// Update with both metadata and optimistic control
794update(
795 todo.id,
796 {
797 metadata: { reason: "admin update" },
798 optimistic: false,
799 },
800 (draft) => {
801 draft.priority = "high"
802 }
804```
805​
806##### `delete`
807​
808```typescript
809// Delete a single item
810delete todo.id
811​
812// Delete multiple items
813delete [todo1.id, todo2.id]
814​
815// Delete with metadata
816delete (todo.id, { metadata: { reason: "completed" } })
817​
818// Delete without optimistic updates (waits for server confirmation)
819delete (todo.id, { optimistic: false })
820​
821// Delete with metadata and optimistic control
822delete (todo.id,
824 metadata: { reason: "admin deletion" },
825 optimistic: false,
826})
827```
828​
829#### Controlling optimistic behavior
830​
831By 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.
832​
833##### When to use `optimistic: false`
834​
835Consider disabling optimistic updates when:
836​
837- **Complex server-side processing**: Inserts that depend on server-side generation (e.g., cascading foreign keys, computed fields)
838- **Validation requirements**: Operations where backend validation might reject the change
839- **Confirmation workflows**: Deletes where UX should wait for confirmation before removing data
840- **Batch operations**: Large operations where optimistic rollback would be disruptive
841​
842##### Behavior differences
843​
844**`optimistic: true` (default)**:
845​
846- Immediately applies mutation to the local store
847- Provides instant UI feedback
848- Requires rollback if server rejects the mutation
849- Best for simple, predictable operations
850​
851**`optimistic: false`**:
852​
853- Does not modify local store until server confirms
854- No immediate UI feedback, but no rollback needed
855- UI updates only after successful server response
856- Best for complex or validation-heavy operations
857​
858```typescript
859// Example: Critical deletion that needs confirmation
860const handleDeleteAccount = () => {
861 // Don't remove from UI until server confirms
862 userCollection.delete(userId, { optimistic: false })
864​
865// Example: Server-generated data
866const handleCreateInvoice = () => {
867 // Server generates invoice number, tax calculations, etc.
868 invoiceCollection.insert(invoiceData, { optimistic: false })
870​
871// Example: Mixed approach in same transaction
872tx.mutate(() => {
873 // Instant UI feedback for simple change
874 todoCollection.update(todoId, (draft) => {
875 draft.completed = true
876 })
877​
878 // Wait for server confirmation for complex change
879 auditCollection.insert(auditRecord, { optimistic: false })
880})
881```
882​
883##### Common workflow: Wait for persistence before navigation
884​
885A common pattern with `optimistic: false` is to wait for the mutation to complete before navigating to a new page or showing success feedback:
886​
887```typescript
888const handleCreatePost = async (postData) => {
889 // Insert without optimistic updates
890 const tx = postsCollection.insert(postData, { optimistic: false })
891​
892 try {
893 // Wait for write to server and sync back to complete
894 await tx.isPersisted.promise
895​
896 // Server write and sync back were successful - safe to navigate
897 navigate(`/posts/${postData.id}`)
898 } catch (error) {
899 // Show error toast or notification
900 toast.error('Failed to create post: ' + error.message)
901 }
903​
904// Works with updates and deletes too
905const handleUpdateTodo = async (todoId, changes) => {
906 const tx = todoCollection.update(
907 todoId,
908 { optimistic: false },
909 (draft) => Object.assign(draft, changes)
910 )
911​
912 try {
913 await tx.isPersisted.promise
914 navigate('/todos')
915 } catch (error) {
916 toast.error('Failed to update todo: ' + error.message)
917 }
919```
920​
921## Usage examples
922​
923Here we illustrate two common ways of using TanStack DB:
924​
9251. [using TanStack Query](#1-tanstack-query) with an existing REST API
9262. [using the ElectricSQL sync engine](#2-electricsql-sync) with a generic ingestion endpoint
927​
928> [!TIP]
929> 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.
930​
931### 1. TanStack Query
932​
933You can use TanStack DB with your existing REST API via TanStack Query.
934​
935The steps are to:
936​
9371. create [`QueryCollection`](#querycollection)s that load data using TanStack Query
9382. implement [`mutationFn`](#mutationfn)s that handle mutations by posting them to your API endpoints
939​
940```tsx
941import { useLiveQuery, createCollection } from "@tanstack/react-db"
942import { queryCollectionOptions } from "@tanstack/query-db-collection"
943​
944// Load data into collections using TanStack Query.
945// It's common to define these in a `collections` module.
946const todoCollection = createCollection(
947 queryCollectionOptions({
948 queryKey: ["todos"],
949 queryFn: async () => fetch("/api/todos"),
950 getKey: (item) => item.id,
951 schema: todoSchema, // any standard schema
952 onInsert: async ({ transaction }) => {
953 const { changes: newTodo } = transaction.mutations[0]
954​
955 // Handle the local write by sending it to your API.
956 await api.todos.create(newTodo)
957 },
958 // also add onUpdate, onDelete as needed.
959 })
961const listCollection = createCollection(
962 queryCollectionOptions({
963 queryKey: ["todo-lists"],
964 queryFn: async () => fetch("/api/todo-lists"),
965 getKey: (item) => item.id,
966 schema: todoListSchema,
967 onInsert: async ({ transaction }) => {
968 const { changes: newTodo } = transaction.mutations[0]
969​
970 // Handle the local write by sending it to your API.
971 await api.todoLists.create(newTodo)
972 },
973 // also add onUpdate, onDelete as needed.
974 })
976​
977const Todos = () => {
978 // Read the data using live queries. Here we show a live
979 // query that joins across two collections.
980 const { data: todos } = useLiveQuery((q) =>
981 q
982 .from({ todo: todoCollection })
983 .join(
984 { list: listCollection },
985 ({ todo, list }) => eq(list.id, todo.list_id),
986 "inner"
987 )
988 .where(({ list }) => eq(list.active, true))
989 .select(({ todo, list }) => ({
990 id: todo.id,
991 text: todo.text,
992 status: todo.status,
993 listName: list.name,
994 }))
995 )
996​
997 // ...
999```
1000​
1001This 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.
1002​
1003### 2. ElectricSQL sync
1004​
1005One 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.
1006​
1007Here, we illustrate this pattern using [ElectricSQL](https://electric-sql.com) as the sync engine.
1008​
1009```tsx
1010import type { Collection } from "@tanstack/db"
1011import type {
1012 MutationFn,
1013 PendingMutation,
1014 createCollection,
1015} from "@tanstack/react-db"
1016import { electricCollectionOptions } from "@tanstack/electric-db-collection"
1017​
1018export const todoCollection = createCollection(
1019 electricCollectionOptions({
1020 id: "todos",
1021 schema: todoSchema,
1022 // Electric syncs data using "shapes". These are filtered views
1023 // on database tables that Electric keeps in sync for you.
1024 shapeOptions: {
1025 url: "https://api.electric-sql.cloud/v1/shape",
1026 params: {
1027 table: "todos",
1028 },
1029 },
1030 getKey: (item) => item.id,
1031 schema: todoSchema,
1032 onInsert: async ({ transaction }) => {
1033 const response = await api.todos.create(transaction.mutations[0].modified)
1034​
1035 return { txid: response.txid }
1036 },
1037 // You can also implement onUpdate, onDelete as needed.
1038 })
1040​
1041const AddTodo = () => {
1042 return (
1043 <Button
1044 onClick={() => todoCollection.insert({ text: "🔥 Make app faster" })}
1045 />
1048```
1049​
1050## React Native
1051​
1052When 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.
1053​
1054Install the `react-native-random-uuid` package:
1055​
1056```bash
1057npm install react-native-random-uuid
1058```
1059​
1060Then import it at the entry point of your React Native app (e.g., in your `App.js` or `index.js`):
1061​
1062```javascript
1063import "react-native-random-uuid"
1064```
1065​
1066This polyfill provides the `crypto.randomUUID()` function that TanStack DB uses internally for generating unique identifiers.
1067​
1068## More info
1069​
1070If you have questions / need help using TanStack DB, let us know on the Discord or start a GitHub discussion:
1071​
1072- [`#db` channel in the TanStack discord](https://discord.gg/yjUNbvbraC)
1073- [GitHub discussions](https://github.com/tanstack/db/discussions)