TanStack DB Skills
TanStack DB is the reactive client store for your API. It provides sub-millisecond live queries, instant optimistic updates, and seamless integration with REST APIs and sync engines like ElectricSQL.
Routing Table
| Topic |
Directory |
When to Use |
| Live Queries |
live-queries/ |
Querying data: filters, joins, aggregations, groupBy, orderBy, subqueries, reactive updates |
| Mutations |
mutations/ |
Writing data: insert/update/delete, optimistic updates, transactions, paced mutations, error handling |
| Collections |
collections/ |
Data sources: QueryCollection, ElectricCollection, local collections, sync modes, collection setup |
| Schemas |
schemas/ |
Validation: schema definition, TInput/TOutput types, transformations, defaults, error handling |
| Electric |
electric/ |
ElectricSQL integration: shapes, txid matching, real-time sync, proxy setup |
Quick Detection
Route to live-queries/ when:
- Building queries with
useLiveQuery or createLiveQueryCollection
- Using
from, where, select, join, groupBy, orderBy
- Working with aggregations (
count, sum, avg, min, max)
- Joining data across multiple collections
- Creating derived/materialized views
- Performance questions about query updates
Route to mutations/ when:
- Using
collection.insert(), collection.update(), collection.delete()
- Creating custom actions with
createOptimisticAction
- Working with transactions via
createTransaction
- Implementing paced mutations (debounce, throttle, queue)
- Handling mutation errors or rollbacks
- Questions about optimistic state lifecycle
Route to collections/ when:
- Setting up a new collection
- Choosing between QueryCollection, ElectricCollection, LocalStorage, etc.
- Configuring sync modes (eager, on-demand, progressive)
- Understanding collection lifecycle
- Loading data from APIs or sync engines
Route to schemas/ when:
- Defining schemas with Zod, Valibot, or other StandardSchema libraries
- Understanding TInput vs TOutput types
- Transforming data (string to Date, etc.)
- Setting default values
- Handling validation errors
Route to electric/ when:
- Setting up ElectricSQL integration
- Working with shapes and real-time sync
- Implementing txid matching for mutations
- Debugging sync issues
- Building an Electric proxy
Core Concepts
import { createCollection, useLiveQuery, eq } from '@tanstack/react-db'
import { queryCollectionOptions } from '@tanstack/query-db-collection'
// 1. Define a collection (data source)
const todoCollection = createCollection(
queryCollectionOptions({
queryKey: ['todos'],
queryFn: async () => fetch('/api/todos').then((r) => r.json()),
getKey: (item) => item.id,
onUpdate: async ({ transaction }) => {
await api.todos.update(
transaction.mutations[0].original.id,
transaction.mutations[0].changes,
)
},
}),
)
// 2. Query with live queries (reactive, incremental updates)
function TodoList() {
const { data: todos } = useLiveQuery((q) =>
q
.from({ todo: todoCollection })
.where(({ todo }) => eq(todo.completed, false))
.orderBy(({ todo }) => todo.createdAt, 'desc'),
)
// 3. Mutate with optimistic updates
const toggleTodo = (id: string) => {
todoCollection.update(id, (draft) => {
draft.completed = !draft.completed
})
}
return (
<ul>
{todos?.map((todo) => (
<li key={todo.id} => toggleTodo(todo.id)}>
{todo.text}
</li>
))}
</ul>
)
}
Data Flow
TanStack DB extends unidirectional data flow beyond the client:
┌─────────────────────────────────────────────────────────────┐
│ OPTIMISTIC LOOP (instant) │
│ User Action → Optimistic State → UI Update │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ PERSISTENCE LOOP (async) │
│ Mutation Handler → Server → Sync Back → Confirmed State │
└─────────────────────────────────────────────────────────────┘
Package Overview
| Package |
Purpose |
@tanstack/db |
Core: collections, queries, mutations |
@tanstack/react-db |
React hooks: useLiveQuery, etc. |
@tanstack/query-db-collection |
REST API integration via TanStack Query |
@tanstack/electric-db-collection |
ElectricSQL real-time sync |
@tanstack/vue-db |
Vue adapter |
@tanstack/angular-db |
Angular adapter |
@tanstack/svelte-db |
Svelte adapter |
@tanstack/solid-db |
Solid adapter |
1---2name: tanstack-db-skills-tanstack-db3description: TanStack DB patterns for reactive client-side data with live queries and optimistic mutations. Use for collections, queries, mutations, schemas, and sync engine integration.4license: MIT5---67# TanStack DB Skills89TanStack DB is the reactive client store for your API. It provides sub-millisecond live queries, instant optimistic updates, and seamless integration with REST APIs and sync engines like ElectricSQL.1011## Routing Table1213| Topic | Directory | When to Use |14| ---------------- | --------------- | ----------------------------------------------------------------------------------------------------- |15| **Live Queries** | `live-queries/` | Querying data: filters, joins, aggregations, groupBy, orderBy, subqueries, reactive updates |16| **Mutations** | `mutations/` | Writing data: insert/update/delete, optimistic updates, transactions, paced mutations, error handling |17| **Collections** | `collections/` | Data sources: QueryCollection, ElectricCollection, local collections, sync modes, collection setup |18| **Schemas** | `schemas/` | Validation: schema definition, TInput/TOutput types, transformations, defaults, error handling |19| **Electric** | `electric/` | ElectricSQL integration: shapes, txid matching, real-time sync, proxy setup |2021## Quick Detection2223**Route to `live-queries/` when:**2425- Building queries with `useLiveQuery` or `createLiveQueryCollection`26- Using `from`, `where`, `select`, `join`, `groupBy`, `orderBy`27- Working with aggregations (`count`, `sum`, `avg`, `min`, `max`)28- Joining data across multiple collections29- Creating derived/materialized views30- Performance questions about query updates3132**Route to `mutations/` when:**3334- Using `collection.insert()`, `collection.update()`, `collection.delete()`35- Creating custom actions with `createOptimisticAction`36- Working with transactions via `createTransaction`37- Implementing paced mutations (debounce, throttle, queue)38- Handling mutation errors or rollbacks39- Questions about optimistic state lifecycle4041**Route to `collections/` when:**4243- Setting up a new collection44- Choosing between QueryCollection, ElectricCollection, LocalStorage, etc.45- Configuring sync modes (eager, on-demand, progressive)46- Understanding collection lifecycle47- Loading data from APIs or sync engines4849**Route to `schemas/` when:**5051- Defining schemas with Zod, Valibot, or other StandardSchema libraries52- Understanding TInput vs TOutput types53- Transforming data (string to Date, etc.)54- Setting default values55- Handling validation errors5657**Route to `electric/` when:**5859- Setting up ElectricSQL integration60- Working with shapes and real-time sync61- Implementing txid matching for mutations62- Debugging sync issues63- Building an Electric proxy6465## Core Concepts6667```tsx68import { createCollection, useLiveQuery, eq } from '@tanstack/react-db'69import { queryCollectionOptions } from '@tanstack/query-db-collection'7071// 1. Define a collection (data source)72const todoCollection = createCollection(73 queryCollectionOptions({74 queryKey: ['todos'],75 queryFn: async () => fetch('/api/todos').then((r) => r.json()),76 getKey: (item) => item.id,77 onUpdate: async ({ transaction }) => {78 await api.todos.update(79 transaction.mutations[0].original.id,80 transaction.mutations[0].changes,81 )82 },83 }),84)8586// 2. Query with live queries (reactive, incremental updates)87function TodoList() {88 const { data: todos } = useLiveQuery((q) =>89 q90 .from({ todo: todoCollection })91 .where(({ todo }) => eq(todo.completed, false))92 .orderBy(({ todo }) => todo.createdAt, 'desc'),93 )9495 // 3. Mutate with optimistic updates96 const toggleTodo = (id: string) => {97 todoCollection.update(id, (draft) => {98 draft.completed = !draft.completed99 })100 }101102 return (103 <ul>104 {todos?.map((todo) => (105 <li key={todo.id} onClick={() => toggleTodo(todo.id)}>106 {todo.text}107 </li>108 ))}109 </ul>110 )111}112```113114## Data Flow115116TanStack DB extends unidirectional data flow beyond the client:117118```119┌─────────────────────────────────────────────────────────────┐120│ OPTIMISTIC LOOP (instant) │121│ User Action → Optimistic State → UI Update │122└─────────────────────────────────────────────────────────────┘123 ↓124┌─────────────────────────────────────────────────────────────┐125│ PERSISTENCE LOOP (async) │126│ Mutation Handler → Server → Sync Back → Confirmed State │127└─────────────────────────────────────────────────────────────┘128```129130## Package Overview131132| Package | Purpose |133| ---------------------------------- | --------------------------------------- |134| `@tanstack/db` | Core: collections, queries, mutations |135| `@tanstack/react-db` | React hooks: useLiveQuery, etc. |136| `@tanstack/query-db-collection` | REST API integration via TanStack Query |137| `@tanstack/electric-db-collection` | ElectricSQL real-time sync |138| `@tanstack/vue-db` | Vue adapter |139| `@tanstack/angular-db` | Angular adapter |140| `@tanstack/svelte-db` | Svelte adapter |141| `@tanstack/solid-db` | Solid adapter |