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

overview.md

607 lines24.0 KB

1---
2title: Overview
3id: overview
4---
5​
6Welcome to the TanStack DB documentation.
7​
8TanStack DB is the reactive client store for your API. It solves the problems of building fast, modern apps, helping you:
9​
10- avoid endpoint sprawl and network waterfalls by loading data into normalized collections
11- optimise client performance with sub-millisecond live queries and real-time reactivity
12- take the network off the interaction path with instant optimistic writes
13​
14Data loading is optimized. Interactions feel instantaneous. Your backend stays simple and your app stays blazing fast. No matter how much data you load.
15​
16## Remove the complexity from building fast, modern apps
17​
18TanStack DB lets you query your data however your components need it, with a blazing-fast local query engine, real-time reactivity and instant optimistic updates.
19​
20Instead of choosing between the least of two evils:
21​
221. **view-specific APIs** - complicating your backend and leading to network waterfalls
232. **load everything and filter** - leading to slow loads and sluggish client performance
24​
25TanStack DB enables a new way:
26​
273. **normalized collections** - keep your backend simple
284. **query-driven sync** - optimizes your data loading
295. **sub-millisecond live queries** - keep your app fast and responsive
30​
31It extends TanStack Query with collections, live queries and optimistic mutations, working seamlessly with REST APIs, sync engines, or any data source.
32​
33## Contents
34​
35- [How it works](#how-it-works) — understand the TanStack DB development model and how the pieces fit together
36- [SSR and hydration](./guides/ssr.md) — use `DbClient` to transport explicit collection rows or live-query result snapshots
37- [SQLite persistence](./guides/sqlite-persistence.md) — retain Collection rows across restarts and save sync metadata for supported adapters
38- [Offline transactions](./guides/offline-transactions.md) — retain pending mutations and retry them later
39- [API reference](#api-reference) — for the primitives and function interfaces
40- [Usage examples](#usage-examples) — examples of common usage patterns
41- [More info](#more-info) — where to find support and more information
42​
43## How it works
44​
45TanStack DB works by:
46​
47- [defining collections](#defining-collections) typed sets of objects that can be populated with data
48- [using live queries](#using-live-queries) to query data from/across collections
49- [making optimistic mutations](#making-optimistic-mutations) using transactional mutators
50​
51```tsx
52import {
53 DbClient,
54 DbProvider,
55 collectionOptions,
56 not,
57 useDbClient,
58 useLiveQuery,
59} from '@tanstack/react-db'
60​
61// Define stable collection descriptors to load data into
62const todoCollection = collectionOptions('todos', () => ({
63 id: 'todos',
64 // ...your config
65 onUpdate: updateMutationFn,
66}))
67​
68function useTodoCollection() {
69 return useDbClient().collection(todoCollection)
71​
72const Todos = () => {
73 const todosCollection = useTodoCollection()
74​
75 // Bind data using live queries
76 const { data: todos } = useLiveQuery({
77 query: (q) =>
78 q.from({ todo: todoCollection }).where(({ todo }) => not(todo.completed)),
79 })
80​
81 const complete = (todo) => {
82 // Instantly applies optimistic state
83 todosCollection.update(todo.id, (draft) => {
84 draft.completed = true
85 })
86 }
87​
88 return (
89 <ul>
90 {todos.map((todo) => (
91 <li key={todo.id} onClick={() => complete(todo)}>
92 {todo.text}
93 </li>
94 ))}
95 </ul>
96 )
98​
99const dbClient = new DbClient()
100​
101const App = () => (
102 <DbProvider client={dbClient}>
103 <Todos />
104 </DbProvider>
106```
107​
108### Defining collections
109​
110Collections 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.
111​
112Collections can be populated in many ways, including:
113​
114- fetching data, for example [from API endpoints using TanStack Query](https://tanstack.com/query/latest)
115- syncing data, for example [using a sync engine like ElectricSQL](https://electric-sql.com/) or [PowerSync](https://powersync.com)
116- storing local data, for example [using localStorage for user preferences and settings](./collections/local-storage-collection.md) or [in-memory client data or UI state](./collections/local-only-collection.md)
117- from live collection queries, creating [derived collections as materialised views](#using-live-queries)
118​
119Once you have your data in collections, you can query across them using live queries in your components.
120​
121#### Sync Modes
122​
123Collections support three sync modes to optimize data loading:
124​
125- **Eager mode** (default): Loads entire collection upfront. Best for <10k rows of mostly static data like user preferences or small reference tables.
126- **On-demand mode**: Loads only what queries request. Best for large datasets (>50k rows), search interfaces, and catalogs where most data won't be accessed.
127- **Progressive mode**: Loads query subset immediately, syncs full dataset in background. Best for collaborative apps needing instant first paint AND sub-millisecond queries.
128​
129With on-demand mode, your component's query becomes the API call:
130​
131```tsx
132const productsCollection = collectionOptions('products', (client) =>
133 queryCollectionOptions({
134 id: 'products',
135 queryKey: ['products'],
136 queryClient: client.requireDependency<QueryClient>('queryClient'),
137 queryFn: async (ctx) => {
138 // Query predicates passed automatically in ctx.meta
139 const params = parseLoadSubsetOptions(ctx.meta?.loadSubsetOptions)
140 return api.getProducts(params) // e.g., GET /api/products?category=electronics&price_lt=100
141 },
142 getKey: (product) => product.id,
143 syncMode: 'on-demand', // ← Enable query-driven sync
144 })
146```
147​
148TanStack DB automatically collapses duplicate requests, performs delta loading when expanding queries, optimizes joins into minimal batched requests, and respects your TanStack Query cache policies. You often end up with _fewer_ network requests than custom view-specific APIs.
149​
150See the [Query Collection documentation](./collections/query-collection.md#queryfn-and-predicate-push-down) for full predicate mapping details.
151​
152### Using live queries
153​
154Live 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.
155​
156TanStack 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.
157​
158**Performance:** Updating one row in a sorted 100,000-item collection completes in ~0.7ms on an M1 Pro MacBook—fast enough that optimistic updates feel truly instantaneous, even with complex queries and large datasets.
159​
160Live queries support joins across collections. This allows you to:
161​
1621. 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
1632. 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
164​
165Every query returns another collection which can _also_ be queried.
166​
167For more details on live queries, see the [Live Queries](./guides/live-queries.md) documentation.
168​
169### Making optimistic mutations
170​
171Collections 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.
172​
173```ts
174// Define collection with persistence handlers
175const todoCollection = collectionOptions('todos', () => ({
176 id: "todos",
177 // ... other config
178 onUpdate: async ({ transaction }) => {
179 const { original, changes } = transaction.mutations[0]
180 await api.todos.update(original.id, changes)
181 },
182}))
183const todosCollection = dbClient.collection(todoCollection)
184​
185// Immediately applies optimistic state
186todosCollection.update(todo.id, (draft) => {
187 draft.completed = true
188})
189```
190​
191The collection maintains optimistic state separately from synced data. When live queries read from the collection, they see a local view that overlays the optimistic mutations on top of the immutable synced data.
192​
193The optimistic state is held until the handler resolves, at which point the data is persisted to the server and synced back. If the handler throws an error, the optimistic state is rolled back.
194​
195For more complex mutations, you can create custom actions with `createOptimisticAction` or custom transactions with `createTransaction`. See the [Mutations guide](./guides/mutations.md) for details.
196​
197### Uni-directional data flow
198​
199This 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:
200​
201<figure>
202 <a href="https://raw.githubusercontent.com/TanStack/db/main/docs/unidirectional-data-flow.lg.png" target="_blank">
203 <img src="https://raw.githubusercontent.com/TanStack/db/main/docs/unidirectional-data-flow.png" />
204 </a>
205</figure>
206​
207With 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.
208​
209## API reference
210​
211### Collections
212​
213TanStack DB provides several built-in collection types for different data sources and use cases. Each collection type has its own detailed documentation page:
214​
215#### Built-in Collection Types
216​
217**Fetch Collections**
218​
219- **[QueryCollection](./collections/query-collection.md)** — Load data into collections using TanStack Query for REST APIs and data fetching.
220​
221**Sync Collections**
222​
223- **[ElectricCollection](./collections/electric-collection.md)** — Sync data into collections from Postgres using ElectricSQL's real-time sync engine.
224​
225- **[TrailBaseCollection](./collections/trailbase-collection.md)** — Sync data into collections using TrailBase's self-hosted backend with real-time subscriptions.
226​
227- **[RxDBCollection](./collections/rxdb-collection.md)** — Integrate with RxDB for offline-first local persistence with powerful replication and sync capabilities.
228​
229- **[PowerSyncCollection](./collections/powersync-collection.md)** — Sync with PowerSync's SQLite-based database for offline-first persistence with real-time synchronization with PostgreSQL, MongoDB, and MySQL backends.
230​
231**Local Collections**
232​
233- **[IndexedDB Collection](./collections/indexeddb-collection.md)** — Persist local browser data in IndexedDB with asynchronous writes and cross-tab notifications.
234​
235- **[LocalStorageCollection](./collections/local-storage-collection.md)** — Store small amounts of local-only state that persists across sessions and syncs across browser tabs.
236​
237- **[LocalOnlyCollection](./collections/local-only-collection.md)** — Manage in-memory client data or UI state that doesn't need persistence or cross-tab sync.
238​
239#### Collection Schemas
240​
241All collections optionally (though strongly recommended) support adding a `schema`.
242​
243If provided, this must be a [Standard Schema](https://standardschema.dev) compatible schema instance, such as [Zod](https://zod.dev), [Valibot](https://valibot.dev), [ArkType](https://arktype.io), or [Effect](https://effect.website/docs/schema/introduction/).
244​
245**What schemas do:**
246​
2471. **Runtime validation** - Ensures data meets your constraints before entering the collection
2482. **Type transformations** - Convert input types to rich output types (e.g., string → Date)
2493. **Default values** - Automatically populate missing fields
2504. **Type safety** - Infer TypeScript types from your schema
251​
252**Example:**
253```typescript
254const todoSchema = z.object({
255 id: z.string(),
256 text: z.string(),
257 completed: z.boolean().default(false),
258 created_at: z.string().transform(val => new Date(val)), // string → Date
259 priority: z.number().default(0)
260})
261​
262const todoCollection = collectionOptions(
263 queryCollectionOptions({
264 id: "todos",
265 schema: todoSchema,
266 // ...
267 })
269const collection = dbClient.collection(todoCollection)
270​
271// Users provide simple inputs
272collection.insert({
273 id: "1",
274 text: "Buy groceries",
275 created_at: "2024-01-01T00:00:00Z" // string
276 // completed and priority filled automatically
277})
278​
279// Collection stores and returns rich types
280const todo = collection.get("1")
281console.log(todo.created_at.getFullYear()) // It's a Date!
282console.log(todo.completed) // false (default)
283```
284​
285The collection will use the schema for its type inference. If you provide a schema, you cannot also pass an explicit type parameter (e.g., `createCollection<Todo>()`).
286​
287**Learn more:** See the [Schemas guide](./guides/schemas.md) for comprehensive documentation on schema validation, type transformations, and best practices.
288​
289#### Creating Custom Collection Types
290​
291You can create your own collection types by implementing the `Collection` interface found in [`../packages/db/src/collection/index.ts`](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts).
292​
293See 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), [`../packages/trailbase-db-collection`](https://github.com/TanStack/db/tree/main/packages/trailbase-db-collection) and [`../packages/powersync-db-collection`](https://github.com/TanStack/db/tree/main/packages/powersync-db-collection) for reference. Also see the [Collection Options Creator guide](./guides/collection-options-creator.md) for a pattern to create reusable collection configuration factories.
294​
295### Live queries
296​
297#### `useLiveQuery` hook
298​
299Use the `useLiveQuery` hook to assign live query results to a state variable in your React components:
300​
301```ts
302import { useLiveQuery } from '@tanstack/react-db'
303import { eq } from '@tanstack/db'
304​
305const Todos = () => {
306 const { data: todos } = useLiveQuery({
307 query: (q) =>
308 q
309 .from({ todo: todoCollection })
310 .where(({ todo }) => eq(todo.completed, false))
311 .orderBy(({ todo }) => todo.created_at, 'asc')
312 .select(({ todo }) => ({
313 id: todo.id,
314 text: todo.text
315 })),
316 })
317​
318 return <List items={ todos } />
320```
321​
322You can also query across collections with joins:
323​
324```ts
325import { useLiveQuery } from '@tanstack/react-db'
326import { eq } from '@tanstack/db'
327​
328const Todos = () => {
329 const { data: todos } = useLiveQuery({
330 query: (q) =>
331 q
332 .from({ todos: todoCollection })
333 .join(
334 { lists: listCollection },
335 ({ todos, lists }) => eq(lists.id, todos.listId),
336 'inner'
337 )
338 .where(({ lists }) => eq(lists.active, true))
339 .select(({ todos, lists }) => ({
340 id: todos.id,
341 title: todos.title,
342 listName: lists.name
343 })),
344 })
345​
346 return <List items={ todos } />
348```
349​
350#### `useLiveSuspenseQuery` hook
351​
352For React Suspense support, use `useLiveSuspenseQuery`. This hook suspends rendering during initial data load and guarantees that `data` is always defined:
353​
354```tsx
355import { useLiveSuspenseQuery } from '@tanstack/react-db'
356import { Suspense } from 'react'
357​
358const Todos = () => {
359 // data is always defined - no need for optional chaining
360 const { data: todos } = useLiveSuspenseQuery({
361 query: (q) =>
362 q
363 .from({ todo: todoCollection })
364 .where(({ todo }) => eq(todo.completed, false)),
365 })
366​
367 return <List items={ todos } />
369​
370const App = () => (
371 <Suspense fallback={<div>Loading...</div>}>
372 <Todos />
373 </Suspense>
375```
376​
377See the [React Suspense section in Live Queries](./guides/live-queries#using-with-react-suspense) for detailed usage patterns and when to use `useLiveSuspenseQuery` vs `useLiveQuery`.
378​
379#### `queryBuilder`
380​
381You can also build queries directly (outside of the component lifecycle) using the underlying `queryBuilder` API:
382​
383```ts
384import { createLiveQueryCollection, eq } from "@tanstack/db"
385​
386const completedTodos = createLiveQueryCollection({
387 startSync: true,
388 query: (q) =>
389 q
390 .from({ todo: todoCollection })
391 .where(({ todo }) => eq(todo.completed, true)),
392})
393​
394const results = completedTodos.toArray
395```
396​
397Note also that:
398​
3991. the query results [are themselves a collection](#derived-collections)
4002. 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
401​
402See the [Live Queries](./guides/live-queries.md) documentation for more details.
403​
404### Transactional mutators
405​
406For more complex mutations beyond simple CRUD operations, TanStack DB provides `createOptimisticAction` and `createTransaction` for creating custom mutations with full control over the mutation lifecycle.
407​
408See the [Mutations guide](./guides/mutations.md) for comprehensive documentation on:
409​
410- Creating custom actions with `createOptimisticAction`
411- Manual transactions with `createTransaction`
412- Mutation merging behavior
413- Controlling optimistic vs non-optimistic updates
414- Handling temporary IDs
415- Transaction lifecycle states
416​
417## Usage examples
418​
419Here we illustrate two common ways of using TanStack DB:
420​
4211. [using TanStack Query](#1-tanstack-query) with an existing REST API
4222. [using a sync engine](#2-sync-engine) for real-time sync with your backend
423​
424> [!TIP]
425> 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.
426​
427### 1. TanStack Query
428​
429You can use TanStack DB with your existing REST API via TanStack Query.
430​
431The steps are to:
432​
4331. create [QueryCollection](./collections/query-collection.md)s that load data using TanStack Query
4342. implement mutation handlers that handle mutations by posting them to your API endpoints
435​
436```tsx
437import {
438 DbClient,
439 DbProvider,
440 collectionOptions,
441 useLiveQuery,
442} from "@tanstack/react-db"
443import { queryCollectionOptions } from "@tanstack/query-db-collection"
444import { QueryClient } from "@tanstack/query-core"
445​
446const queryClient = new QueryClient()
447const dbClient = new DbClient({ queryClient })
448​
449// Load data into collections using TanStack Query.
450// It's common to define these in a `collections` module.
451const todoCollection = collectionOptions("todos", (client) =>
452 queryCollectionOptions({
453 id: "todos",
454 queryKey: ["todos"],
455 queryClient: client.requireDependency<QueryClient>("queryClient"),
456 queryFn: async () => fetch("/api/todos").then((response) => response.json()),
457 getKey: (item) => item.id,
458 schema: todoSchema, // any standard schema
459 onInsert: async ({ transaction, collection }) => {
460 const { changes: newTodo } = transaction.mutations[0]
461​
462 // Handle the local write by sending it to your API.
463 await api.todos.create(newTodo)
464 await collection.utils.refetch()
465 // Prevent the pre-1.0 compatibility wrapper from refetching again.
466 return { refetch: false }
467 },
468 // also add onUpdate, onDelete as needed.
469 })
471const listCollection = collectionOptions("todo-lists", (client) =>
472 queryCollectionOptions({
473 id: "todo-lists",
474 queryKey: ["todo-lists"],
475 queryClient: client.requireDependency<QueryClient>("queryClient"),
476 queryFn: async () =>
477 fetch("/api/todo-lists").then((response) => response.json()),
478 getKey: (item) => item.id,
479 schema: todoListSchema,
480 onInsert: async ({ transaction, collection }) => {
481 const { changes: newTodo } = transaction.mutations[0]
482​
483 // Handle the local write by sending it to your API.
484 await api.todoLists.create(newTodo)
485 await collection.utils.refetch()
486 // Prevent the pre-1.0 compatibility wrapper from refetching again.
487 return { refetch: false }
488 },
489 // also add onUpdate, onDelete as needed.
490 })
492​
493const Todos = () => {
494 // Read the data using live queries. Here we show a live
495 // query that joins across two collections.
496 const { data: todos } = useLiveQuery({
497 query: (q) =>
498 q
499 .from({ todo: todoCollection })
500 .join(
501 { list: listCollection },
502 ({ todo, list }) => eq(list.id, todo.list_id),
503 "inner"
504 )
505 .where(({ list }) => eq(list.active, true))
506 .select(({ todo, list }) => ({
507 id: todo.id,
508 text: todo.text,
509 status: todo.status,
510 listName: list.name,
511 })),
512 })
513​
514 // ...
516​
517const App = () => (
518 <DbProvider client={dbClient}>
519 <Todos />
520 </DbProvider>
522```
523​
524This 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.
525​
526### 2. Sync Engine
527​
528One 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.
529​
530#### Why Sync Engines?
531​
532While TanStack DB works great with REST APIs, sync engines provide powerful benefits:
533​
534- **Easy real-time updates**: No WebSocket plumbing—write to your database and changes stream automatically to all clients
535- **Automatic side-effects**: When a mutation triggers cascading changes across tables, all affected data syncs automatically without manual cache invalidation
536- **Efficient delta updates**: Only changed rows cross the wire, making it practical to load large datasets client-side
537​
538This pattern enables the "load everything once" approach that makes apps like Linear and Figma feel instant.
539​
540Here, we illustrate this pattern using [ElectricSQL](https://electric-sql.com) as the sync engine, but this pattern also works with other sync engines like [PowerSync](https://www.powersync.com/?utm_source=tanstack&utm_campaign=tanstack_partner), [RxDB](https://rxdb.info/), and [TrailBase](https://trailbase.io/).
541​
542```tsx
543import type {
544 MutationFn,
545 PendingMutation,
546} from "@tanstack/react-db"
547import { collectionOptions, useDbClient } from "@tanstack/react-db"
548import { electricCollectionOptions } from "@tanstack/electric-db-collection"
549​
550export const todoCollection = collectionOptions(
551 electricCollectionOptions({
552 id: "todos",
553 schema: todoSchema,
554 // Electric syncs data using "shapes". These are filtered views
555 // on database tables that Electric keeps in sync for you.
556 shapeOptions: {
557 url: "https://api.electric-sql.cloud/v1/shape",
558 params: {
559 table: "todos",
560 },
561 },
562 getKey: (item) => item.id,
563 onInsert: async ({ transaction, collection }) => {
564 const response = await api.todos.create(transaction.mutations[0].modified)
565​
566 // Wait for txid to sync
567 await collection.utils.awaitTxId(response.txid)
568 },
569 // You can also implement onUpdate, onDelete as needed.
570 })
572​
573const AddTodo = () => {
574 const todosCollection = useDbClient().collection(todoCollection)
575​
576 return (
577 <Button
578 onClick={() => todosCollection.insert({ text: "🔥 Make app faster" })}
579 />
580 )
582```
583​
584## React Native
585​
586When 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.
587​
588Install the `react-native-random-uuid` package:
589​
590```bash
591npm install react-native-random-uuid
592```
593​
594Then import it at the entry point of your React Native app (e.g., in your `App.js` or `index.js`):
595​
596```javascript
597import "react-native-random-uuid"
598```
599​
600This polyfill provides the `crypto.randomUUID()` function that TanStack DB uses internally for generating unique identifiers.
601​
602## More info
603​
604If you have questions / need help using TanStack DB, let us know on the Discord or start a GitHub discussion:
605​
606- [`#db` channel in the TanStack discord](https://discord.gg/yjUNbvbraC)
607- [GitHub discussions](https://github.com/tanstack/db/discussions)