tanstack-store

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

TanStack Store

TanStack Store

Overview

概述

TanStack Store is a lightweight, framework-agnostic reactive state management library with type-safe updates, derived computations, batched mutations, and effect management. It powers the core of TanStack libraries internally and can be used as a standalone state solution. Framework adapters are available for React, Vue, Solid, Angular, and Svelte.
Core primitives:
  • Store — reactive container with
    setState
    , subscriptions, and lifecycle hooks
  • Derived — lazily computed values that track Store/Derived dependencies
  • Effect — side-effect runner triggered by dependency changes
  • batch — groups multiple updates so subscribers fire once
When to use: Shared reactive state across components, derived/computed values from multiple stores, batched state updates, framework-agnostic state logic reusable across React/Vue/Solid/Angular/Svelte, lightweight alternative to Redux/Zustand/MobX.
When NOT to use: Server state and caching (TanStack Query), complex normalized state with middleware (Redux Toolkit), form state management (TanStack Form), simple component-local state (useState/useSignal).
Key characteristics:
  • Tiny bundle size with zero dependencies
  • Immutable update model (always return new references from
    setState
    )
  • Lazy evaluation for Derived values (recompute only when accessed after change)
  • Explicit mount/unmount lifecycle for Derived and Effect (no automatic cleanup)
TanStack Store 是一款轻量级、与框架无关的响应式状态管理库,支持类型安全的更新、派生计算、批量变更以及副作用管理。它是 TanStack 系列库的核心底层实现,也可作为独立的状态管理方案使用。目前已提供 React、Vue、Solid、Angular 和 Svelte 的框架适配器。
核心原语:
  • Store — 具备
    setState
    、订阅功能和生命周期钩子的响应式容器
  • Derived — 延迟计算的值,可跟踪 Store/Derived 的依赖关系
  • Effect — 由依赖变化触发的副作用执行器
  • batch — 将多个更新操作分组,使订阅者仅触发一次回调
适用场景: 跨组件共享响应式状态、基于多个 Store 生成派生/计算值、批量状态更新、可在 React/Vue/Solid/Angular/Svelte 间复用的与框架无关的状态逻辑、Redux/Zustand/MobX 的轻量替代方案。
不适用场景: 服务端状态与缓存(推荐使用 TanStack Query)、带中间件的复杂规范化状态(推荐使用 Redux Toolkit)、表单状态管理(推荐使用 TanStack Form)、简单的组件局部状态(推荐使用 useState/useSignal)。
关键特性:
  • 极小的包体积,无任何依赖
  • 不可变更新模型(始终从
    setState
    返回新的引用)
  • Derived 值的延迟计算(仅在依赖变化且被访问时重新计算)
  • Derived 和 Effect 具备显式的挂载/卸载生命周期(无自动清理机制)

Installation

安装

PackageUse Case
@tanstack/store
Framework-agnostic core
@tanstack/react-store
React adapter (re-exports core)
@tanstack/vue-store
Vue adapter
@tanstack/solid-store
Solid adapter
@tanstack/angular-store
Angular adapter
@tanstack/svelte-store
Svelte adapter
Framework packages re-export the core
Store
,
Derived
,
Effect
, and
batch
— install only the framework package, not both.
包名使用场景
@tanstack/store
与框架无关的核心库
@tanstack/react-store
React 适配器(重导出核心库)
@tanstack/vue-store
Vue 适配器
@tanstack/solid-store
Solid 适配器
@tanstack/angular-store
Angular 适配器
@tanstack/svelte-store
Svelte 适配器
框架包会重导出核心的
Store
Derived
Effect
batch
——只需安装对应框架的包,无需同时安装核心包。

Quick Reference

快速参考

PatternAPIKey Points
Create store
new Store(initialState, options?)
Generic over
TState
and
TUpdater
Read state
store.state
Synchronous property access
Previous state
store.prevState
Value before last
setState
call
Update state
store.setState((prev) => newState)
Accepts updater function or direct value
Subscribe
store.subscribe(listener)
Returns unsubscribe function
Derived value
new Derived({ deps, fn })
Lazily recomputes when dependencies change
Mount derived
derived.mount()
Required to activate dependency tracking
Derived from derivedNest
Derived
in another
deps
Forms a computation graph
Batch updates
batch(() => { ... })
Subscribers notified once after all updates
Side effects
new Effect({ deps, fn, eager? })
Runs fn when dependencies change
Mount effect
effect.mount()
Required to start listening
React binding
useStore(store, selector?)
Re-renders only when selected value changes
Shallow compare
useStore(store, selector, shallow)
Prevents re-renders for structurally equal objects
Lifecycle: subscribe
onSubscribe
option
Fires on first subscriber, cleanup on last
Lifecycle: update
onUpdate
option
Fires after every state change
Custom updater
updateFn
option
Replace default setState behavior
Previous deps
fn: ({ prevDepVals })
Compare current vs previous dependency values
Dep vals access
fn: ({ currDepVals })
Array ordered by
deps
declaration order
模式API关键要点
创建Store
new Store(initialState, options?)
基于
TState
TUpdater
实现泛型支持
读取状态
store.state
同步属性访问
历史状态
store.prevState
上一次
setState
调用前的值
更新状态
store.setState((prev) => newState)
支持更新器函数或直接传入新值
订阅状态
store.subscribe(listener)
返回取消订阅的函数
派生值
new Derived({ deps, fn })
仅在依赖变化且被访问时重新计算
挂载派生值
derived.mount()
必须调用以激活依赖追踪
基于派生值创建派生在另一个
deps
中嵌套
Derived
形成计算图
批量更新
batch(() => { ... })
所有更新完成后仅通知订阅者一次
副作用
new Effect({ deps, fn, eager? })
当依赖变化时执行指定函数
挂载副作用
effect.mount()
必须调用以开始监听依赖变化
React绑定
useStore(store, selector?)
仅当选中的值变化时触发重渲染
浅比较
useStore(store, selector, shallow)
避免结构相等的对象触发不必要的重渲染
生命周期:订阅
onSubscribe
选项
首次订阅时触发,最后一个订阅取消时执行清理
生命周期:更新
onUpdate
选项
每次状态变化后触发
自定义更新器
updateFn
选项
替换默认的setState行为
历史依赖值
fn: ({ prevDepVals })
对比当前与历史的依赖值
依赖值访问
fn: ({ currDepVals })
deps
声明顺序排列的数组

Common Mistakes

常见错误

MistakeCorrect Pattern
Reading
derived.state
without mounting
Call
derived.mount()
before accessing state
Forgetting to unmount derived/effectStore the cleanup function and call it on teardown
Multiple
setState
calls without batching
Wrap related updates in
batch()
to avoid intermediate recomputation
Selecting objects in
useStore
without
shallow
Pass
shallow
as third argument to prevent unnecessary re-renders
Mutating state object directlyAlways return a new object from
setState
updater
Subscribing inside render without cleanupUse
useStore
hook in React instead of manual
subscribe
Creating stores inside React componentsInstantiate stores outside components or in a ref/useState
Not including all deps in DerivedList every Store/Derived dependency in the
deps
array
Mounting Derived deps after the parentMount leaf dependencies before parent Derived values
Using
@tanstack/store
with React directly
Install
@tanstack/react-store
which re-exports core
错误操作正确做法
未挂载就读取
derived.state
在访问状态前调用
derived.mount()
忘记卸载派生值/副作用保存清理函数并在组件卸载时调用
多次
setState
调用未使用批量更新
将相关更新包裹在
batch()
中,避免中间状态的重复计算
useStore
中选择对象时未使用
shallow
传入
shallow
作为第三个参数,防止不必要的重渲染
直接修改状态对象始终从
setState
更新器中返回新对象
在渲染函数内部订阅且未清理在React中使用
useStore
钩子替代手动
subscribe
在React组件内部创建Store实例在组件外部实例化Store,或使用ref/useState存储实例
Derived未包含所有依赖
deps
数组中列出所有Store/Derived依赖
父Derived挂载后才挂载其依赖的Derived在挂载父Derived值之前先挂载叶子节点的依赖
直接在React中使用
@tanstack/store
安装重导出核心库的
@tanstack/react-store

Delegation

任务委托

  • Server state and caching: Delegate to the
    tanstack-query
    skill if available. Otherwise, recommend:
    npx skills add oakoss/agent-skills --skill tanstack-query
  • React component patterns: Delegate to framework-specific skills for component architecture
  • Form state management: Delegate to the
    tanstack-form
    skill if available. Otherwise, recommend:
    npx skills add oakoss/agent-skills --skill tanstack-form
  • Query pattern discovery: Use
    Explore
    agent to find examples in the codebase
  • Code review: Delegate to
    code-reviewer
    agent for store architecture review
  • 服务端状态与缓存:如果
    tanstack-query
    技能可用,可委托给该技能。否则,推荐执行:
    npx skills add oakoss/agent-skills --skill tanstack-query
  • React组件模式:委托给框架特定的技能处理组件架构相关问题
  • 表单状态管理:如果
    tanstack-form
    技能可用,可委托给该技能。否则,推荐执行:
    npx skills add oakoss/agent-skills --skill tanstack-form
  • 查询模式发现:使用
    Explore
    agent在代码库中查找示例
  • 代码审查:委托给
    code-reviewer
    agent进行Store架构审查

References

参考资料

  • Core concepts: Store, setState, subscriptions, and lifecycle hooks
  • Derived state: computed values, dependency tracking, and batching
  • React integration: useStore hook, selectors, and performance
  • 核心概念:Store、setState、订阅与生命周期钩子
  • 派生状态:计算值、依赖追踪与批量更新
  • React集成:useStore钩子、选择器与性能优化