tanstack-db

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

TanStack DB

TanStack DB

Overview

概述

TanStack DB is a reactive client store built on differential dataflow that extends TanStack Query with collections, live queries, and optimistic mutations. It normalizes data into typed collections, enables sub-millisecond cross-collection queries, and provides instant optimistic updates with automatic rollback on failure.
When to use: Reactive UIs needing local-first data, cross-collection joins with live updates, optimistic mutations with automatic sync, real-time sync via ElectricSQL or other backends, apps that outgrow TanStack Query's per-query caching model.
When NOT to use: Simple fetch-and-display (TanStack Query alone suffices), server-components-only apps, purely synchronous local state (useState/Zustand), GraphQL with normalized caching (Apollo/urql).
TanStack DB is currently in beta. APIs may change between releases.
TanStack DB 是一款基于差分数据流构建的响应式客户端存储库,它扩展了 TanStack Query 的功能,新增了集合、实时查询和乐观更新特性。它会将数据规范化为类型化集合,支持亚毫秒级的跨集合查询,并提供即时的乐观更新功能,失败时会自动回滚。
适用场景:需要本地优先数据、带实时更新的跨集合关联查询、带自动同步的乐观更新、通过ElectricSQL或其他后端实现实时同步,以及超出TanStack Query单查询缓存模型能力的应用。
不适用场景:简单的获取并展示场景(仅使用TanStack Query即可满足需求)、仅服务端组件的应用、纯同步本地状态(使用useState/Zustand即可)、带规范化缓存的GraphQL场景(使用Apollo/urql)。
TanStack DB 目前处于 beta 阶段。不同版本间API可能会发生变化。

Quick Reference

快速参考

PatternAPIKey Points
Create collection
createCollection(queryCollectionOptions({...}))
Define typed set of objects with
getKey
Live query (React)
useLiveQuery((q) => q.from({...}).where(...))
Auto-updates when underlying data changes
Filter
.where(({ t }) => eq(t.field, value))
Supports
eq
,
gt
,
lt
,
like
,
and
,
or
,
not
Select fields
.select(({ t }) => ({ id: t.id, name: t.name }))
Project specific fields from collections
Order results
.orderBy(({ t }) => t.field, 'asc')
Sort ascending or descending
Join collections
.join({ b: collB }, ({ a, b }) => eq(...), 'inner')
Cross-collection joins with type safety
Group and aggregate
.groupBy(...).select(({ t }) => ({ count: count(t.id) }))
Supports
count
,
sum
,
avg
,
min
,
max
Insert
collection.insert({ ...data })
Optimistic insert, syncs via
onInsert
handler
Update
collection.update(key, (draft) => { ... })
Immer-style draft mutation, syncs via
onUpdate
Delete
collection.delete(key)
Optimistic delete, syncs via
onDelete
handler
Electric sync
electricCollectionOptions({ shapeOptions: {...} })
Real-time Postgres sync via ElectricSQL
Live query coll.
liveQueryCollectionOptions({ query })
Derived collection from live query definition
Local storage
localStorageCollectionOptions({...})
Persistent local data, syncs across tabs
模式API核心要点
创建集合
createCollection(queryCollectionOptions({...}))
定义带
getKey
的类型化对象集合
实时查询(React)
useLiveQuery((q) => q.from({...}).where(...))
底层数据变化时自动更新
筛选
.where(({ t }) => eq(t.field, value))
支持
eq
,
gt
,
lt
,
like
,
and
,
or
,
not
字段选择
.select(({ t }) => ({ id: t.id, name: t.name }))
从集合中指定字段投影
结果排序
.orderBy(({ t }) => t.field, 'asc')
支持升序或降序排序
集合关联
.join({ b: collB }, ({ a, b }) => eq(...), 'inner')
带类型安全的跨集合关联查询
分组与聚合
.groupBy(...).select(({ t }) => ({ count: count(t.id) }))
支持
count
,
sum
,
avg
,
min
,
max
插入
collection.insert({ ...data })
乐观插入,通过
onInsert
处理函数同步
更新
collection.update(key, (draft) => { ... })
Immer风格的草稿更新,通过
onUpdate
同步
删除
collection.delete(key)
乐观删除,通过
onDelete
处理函数同步
Electric同步
electricCollectionOptions({ shapeOptions: {...} })
通过ElectricSQL实现实时Postgres同步
实时查询集合
liveQueryCollectionOptions({ query })
基于实时查询定义的派生集合
本地存储
localStorageCollectionOptions({...})
持久化本地数据,支持跨标签页同步

Sync Modes (v0.5+)

同步模式(v0.5+)

ModeBehaviorUse Case
Eager (default)Loads all records on collection initSmall datasets (< 1k rows)
On-demandLoads only what queries request (predicate pushdown)Large datasets, selective loading
ProgressiveFast first paint, full dataset syncs in backgroundBest of both, scales to 100k+
模式行为适用场景
即时加载(默认)集合初始化时加载所有记录小型数据集(< 1k行)
按需加载仅加载查询请求的数据(谓词下推)大型数据集、选择性加载
渐进式加载快速首次渲染,后台同步完整数据集兼顾两者优势,可扩展至10万+条数据

Common Mistakes

常见错误

MistakeCorrect Pattern
Using TanStack Query directly for local stateUse collections with live queries for reactive local data
Forgetting
getKey
in collection config
Always provide
getKey
to identify items uniquely
Not providing persistence handlersDefine
onInsert
/
onUpdate
/
onDelete
to sync with server
Using
useQuery
instead of
useLiveQuery
useLiveQuery
provides reactive cross-collection queries
Creating collections inside componentsDefine collections at module scope, outside components
Importing from
@tanstack/db
in React apps
Import from
@tanstack/react-db
(re-exports core)
Expecting automatic server sync without configCollections require explicit persistence handlers for sync
Not installing collection type packageInstall
@tanstack/query-db-collection
for REST API usage
错误正确做法
直接使用TanStack Query处理本地状态结合集合与实时查询处理响应式本地数据
集合配置中遗漏
getKey
始终提供
getKey
来唯一标识条目
未提供持久化处理函数定义
onInsert
/
onUpdate
/
onDelete
以与服务器同步
使用
useQuery
而非
useLiveQuery
useLiveQuery
提供响应式跨集合查询能力
在组件内部创建集合在模块作用域、组件外部定义集合
React应用中从
@tanstack/db
导入
@tanstack/react-db
导入(会重导出核心功能)
期望无需配置即可自动与服务器同步集合需要显式的持久化处理函数才能实现同步
未安装集合类型包安装
@tanstack/query-db-collection
以用于REST API场景

Delegation

任务委托

If the
tanstack-query
skill is available, delegate TanStack Query-specific patterns (query keys, cache invalidation, SSR) to it. Otherwise, recommend:
npx skills add oakoss/agent-skills --skill tanstack-query
If the
electricsql
skill is available, delegate ElectricSQL setup, shapes, auth proxy, and write patterns to it. Otherwise, recommend:
pnpm dlx skills add oakoss/agent-skills -s electricsql -a claude-code -y
If the
local-first
skill is available, delegate architecture decisions, sync engine comparison, and conflict resolution to it. Otherwise, recommend:
pnpm dlx skills add oakoss/agent-skills -s local-first -a claude-code -y
  • Query pattern discovery: Use
    Explore
    agent
  • Architecture review: Use
    Task
    agent
如果
tanstack-query
技能可用,将TanStack Query特定的模式(查询键、缓存失效、SSR)委托给该技能处理。 否则,推荐执行:
npx skills add oakoss/agent-skills --skill tanstack-query
如果
electricsql
技能可用,将ElectricSQL的设置、数据结构、认证代理和写入模式委托给该技能处理。 否则,推荐执行:
pnpm dlx skills add oakoss/agent-skills -s electricsql -a claude-code -y
如果
local-first
技能可用,将架构决策、同步引擎对比和冲突解决相关任务委托给该技能处理。 否则,推荐执行:
pnpm dlx skills add oakoss/agent-skills -s local-first -a claude-code -y
  • 查询模式探索:使用
    Explore
    agent
  • 架构评审:使用
    Task
    agent

References

参考资料

  • Setup, installation, and collection configuration
  • Live queries, filtering, joins, and aggregations
  • Optimistic mutations, persistence handlers, and sync patterns
  • ElectricSQL integration, electric collections, and txid patterns
  • Error class hierarchy, transaction states, and rollback patterns
  • Local-only and localStorage collections with cross-tab sync
  • Cross-collection transactions, joins, batching, and lifecycle
  • 安装、配置与集合设置
  • 实时查询、过滤、关联查询与聚合
  • 乐观更新、持久化处理函数与同步模式
  • ElectricSQL集成、Electric集合与txid模式
  • 错误类层级、事务状态与回滚模式
  • 纯本地与localStorage集合及跨标签页同步
  • 跨集合事务、关联查询、批量处理与生命周期