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

overview.md

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