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

overview.md

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