SuperAPI AI 工具集

state-management

前端与建站

查看项目

更新于 10-14 14:18

技能介绍

用途

该技能提供 TanStack Query v5 和 Zustand v5 的全面模式,用于指导 AI 智能体或 LLM 处理服务器状态与客户端状态管理。适用于从 API 获取数据、管理服务器状态与缓存、处理变更和乐观更新、创建客户端 store,以及结合 React Query 与 Zustand 的场景。

主要能力

文档包含 26+ 条规则,按优先级分类:

  • React Query 基础(CRITICAL,前缀 rq-):QueryClient 与 Provider 设置、useQuery 基础模式、查询键组织、加载与错误状态处理、条件查询。
  • Zustand store 模式(CRITICAL,前缀 zs-):创建基础 store、TypeScript store 模式、高效选择器、action 模式、状态持久化。
  • 缓存与失效(HIGH,前缀 cache-):配置 staleTime、配置 gcTime、查询失效、预取数据、设置初始数据。
  • 变更与更新(HIGH,前缀 mut-):基础 useMutation、onSuccess/onError 回调、变更后失效、直接缓存更新。
  • 乐观更新(MEDIUM,前缀 opt-):基础乐观更新、错误回滚、使用变更变量。
  • DevTools 与调试(MEDIUM,前缀 dev-):React Query DevTools、Zustand DevTools、调试策略。
  • 高级模式(LOW,前缀 adv-):无限滚动、并行请求、依赖查询、结合 React Query 与 Zustand。

使用方式

规则文件位于 rules/ 目录下,包括 rq-usequery.md、rq-query-keys.md、rq-mutation-setup.md、rq-optimistic-updates.md、zs-create-store.md、zs-persist.md、rq-query-invalidation.md、rq-prefetching.md 等,可阅读各文件获取详细说明和代码示例。

QueryClient 设置示例

// lib/queryClient.ts
import { QueryClient } from '@tanstack/react-query'

export const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 1000 * 60 * 5, // 5 minutes
      gcTime: 1000 * 60 * 30,   // 30 minutes (formerly cacheTime)
      retry: 1,
      refetchOnWindowFocus: false,
    },
  },
})

查询键工厂示例

// lib/queryKeys.ts
export const queryKeys = {
  posts: {
    all: ['posts'] as const,
    lists: () => [...queryKeys.posts.all, 'list'] as const,
    list: (filters: PostFilters) =>
      [...queryKeys.posts.lists(), filters] as const,
    details: () => [...queryKeys.posts.all, 'detail'] as const,
    detail: (id: number) => [...queryKeys.posts.details(), id] as const,
  },
  users: {
    all: ['users'] as const,
    detail: (id: number) => [...queryKeys.users.all, id] as const,
    posts: (userId: number) => [...queryKeys.users.all, userId, 'posts'] as const,
  },
}

Zustand store 示例

// stores/useCounterStore.ts
import { create } from 'zustand'

interface CounterState {
  count: number
  increment: () => void
  decrement: () => void
  reset: () => void
}

export const useCounterStore = create<CounterState>((set) => ({
  count: 0,
  increment: () => set((state) => ({ count: state.count + 1 })),
  decrement: () => set((state) => ({ count: state.count - 1 })),
  reset: () => set({ count: 0 }),
}))

适用场景

  • 从 API 获取数据并需要缓存管理的前端应用。
  • 需要处理变更和乐观更新的交互式界面。
  • 需要全局客户端状态(如 UI 状态)的 React 应用。
  • 结合服务器状态与客户端状态的复杂场景。

限制与注意事项

v5 破坏性变更

TanStack Query v5:

  • cacheTime → gcTime
  • keepPreviousData 选项 → placeholderData: keepPreviousData(导入的 helper)
  • isPreviousData → isPlaceholderData
  • useQuery 移除 onSuccess/onError/onSettled — 在 useMutation 上仍然有效
  • useQuery 移除 suspense: true → 使用 useSuspenseQuery

Zustand v5:

  • 移除作为第二个参数的 shallow → 使用来自 zustand/shallow 的 useShallow
  • 返回新引用的选择器需要 useShallow 以避免无限循环

安全:持久化中间件

切勿将认证令牌、密码或密钥持久化到 localStorage/sessionStorage。使用 partialize 仅持久化非敏感状态。通过 HttpOnly cookie 在服务端管理令牌。

其他

该技能按原样提供,用于教育和开发目的。React Query 由 TanStack 以 MIT 许可,Zustand 由 Poimandres (pmnd.rs) 以 MIT 许可。