tanstack-query-best-practices

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

TanStack Query Best Practices

TanStack Query 最佳实践

Comprehensive guidelines for implementing TanStack Query (React Query) patterns in React applications. These rules optimize data fetching, caching, mutations, and server state synchronization.
本文为React应用中实现TanStack Query(React Query)模式提供全面指南,这些规则可优化数据获取、缓存、变更操作及服务端状态同步。

When to Apply

适用场景

  • Creating new data fetching logic
  • Setting up query configurations
  • Implementing mutations and optimistic updates
  • Configuring caching strategies
  • Integrating with SSR/SSG
  • Refactoring existing data fetching code
  • 创建新的数据获取逻辑
  • 配置查询参数
  • 实现变更操作与乐观更新
  • 配置缓存策略
  • 与SSR/SSG集成
  • 重构现有数据获取代码

Rule Categories by Priority

按优先级划分的规则类别

PriorityCategoryRulesImpact
CRITICALQuery Keys5 rulesPrevents cache bugs and data inconsistencies
CRITICALCaching5 rulesOptimizes performance and data freshness
HIGHMutations6 rulesEnsures data integrity and UI consistency
HIGHError Handling3 rulesPrevents poor user experiences
MEDIUMPrefetching4 rulesImproves perceived performance
MEDIUMParallel Queries2 rulesEnables dynamic parallel fetching
MEDIUMInfinite Queries3 rulesPrevents pagination bugs
MEDIUMSSR Integration4 rulesEnables proper hydration
LOWPerformance4 rulesReduces unnecessary re-renders
LOWOffline Support2 rulesEnables offline-first patterns
优先级类别规则数量影响
关键(CRITICAL)查询键(Query Keys)5条规则避免缓存错误和数据不一致
关键(CRITICAL)缓存(Caching)5条规则优化性能与数据新鲜度
高(HIGH)变更操作(Mutations)6条规则确保数据完整性与UI一致性
高(HIGH)错误处理(Error Handling)3条规则避免糟糕的用户体验
中(MEDIUM)预获取(Prefetching)4条规则提升感知性能
中(MEDIUM)并行查询(Parallel Queries)2条规则支持动态并行获取
中(MEDIUM)无限滚动查询(Infinite Queries)3条规则避免分页错误
中(MEDIUM)SSR集成(SSR Integration)4条规则实现正确的水合(hydration)
低(LOW)性能优化(Performance)4条规则减少不必要的重渲染
低(LOW)离线支持(Offline Support)2条规则支持离线优先模式

Quick Reference

快速参考

Query Keys (Prefix:
qk-
)

查询键(前缀:
qk-

  • qk-array-structure
    — Always use arrays for query keys
  • qk-include-dependencies
    — Include all variables the query depends on
  • qk-hierarchical-organization
    — Organize keys hierarchically (entity → id → filters)
  • qk-factory-pattern
    — Use query key factories for complex applications
  • qk-serializable
    — Ensure all key parts are JSON-serializable
  • qk-array-structure
    — 始终使用数组作为查询键
  • qk-include-dependencies
    — 包含查询依赖的所有变量
  • qk-hierarchical-organization
    — 按层级组织键(实体 → ID → 筛选条件)
  • qk-factory-pattern
    — 在复杂应用中使用查询键工厂模式
  • qk-serializable
    — 确保键的所有部分均可JSON序列化

Caching (Prefix:
cache-
)

缓存(前缀:
cache-

  • cache-stale-time
    — Set appropriate staleTime based on data volatility
  • cache-gc-time
    — Configure gcTime for inactive query retention
  • cache-defaults
    — Set sensible defaults at QueryClient level
  • cache-invalidation
    — Use targeted invalidation over broad patterns
  • cache-placeholder-vs-initial
    — Understand placeholder vs initial data differences
  • cache-stale-time
    — 根据数据波动情况设置合适的staleTime
  • cache-gc-time
    — 配置gcTime以保留非活跃查询
  • cache-defaults
    — 在QueryClient层面设置合理的默认值
  • cache-invalidation
    — 使用针对性的失效策略而非宽泛模式
  • cache-placeholder-vs-initial
    — 理解占位数据与初始数据的区别

Mutations (Prefix:
mut-
)

变更操作(前缀:
mut-

  • mut-invalidate-queries
    — Always invalidate related queries after mutations
  • mut-optimistic-updates
    — Implement optimistic updates for responsive UI
  • mut-rollback-context
    — Provide rollback context from onMutate
  • mut-error-handling
    — Handle mutation errors gracefully
  • mut-loading-states
    — Use isPending for mutation loading states
  • mut-mutation-state
    — Use useMutationState for cross-component tracking
  • mut-invalidate-queries
    — 变更后始终使相关查询失效
  • mut-optimistic-updates
    — 实现乐观更新以获得响应式UI
  • mut-rollback-context
    — 从onMutate中提供回滚上下文
  • mut-error-handling
    — 优雅处理变更操作错误
  • mut-loading-states
    — 使用isPending表示变更加载状态
  • mut-mutation-state
    — 使用useMutationState实现跨组件状态追踪

Error Handling (Prefix:
err-
)

错误处理(前缀:
err-

  • err-error-boundaries
    — Use error boundaries with useQueryErrorResetBoundary
  • err-retry-config
    — Configure retry logic appropriately
  • err-fallback-data
    — Provide fallback data when appropriate
  • err-error-boundaries
    — 将错误边界与useQueryErrorResetBoundary结合使用
  • err-retry-config
    — 合理配置重试逻辑
  • err-fallback-data
    — 适时提供降级数据

Prefetching (Prefix:
pf-
)

预获取(前缀:
pf-

  • pf-intent-prefetch
    — Prefetch on user intent (hover, focus)
  • pf-route-prefetch
    — Prefetch data during route transitions
  • pf-stale-time-config
    — Set staleTime when prefetching
  • pf-ensure-query-data
    — Use ensureQueryData for conditional prefetching
  • pf-intent-prefetch
    — 在用户有操作意图时(如悬停、聚焦)预获取数据
  • pf-route-prefetch
    — 在路由切换期间预获取数据
  • pf-stale-time-config
    — 预获取时设置staleTime
  • pf-ensure-query-data
    — 使用ensureQueryData实现条件式预获取

Infinite Queries (Prefix:
inf-
)

无限滚动查询(前缀:
inf-

  • inf-page-params
    — Always provide getNextPageParam
  • inf-loading-guards
    — Check isFetchingNextPage before fetching more
  • inf-max-pages
    — Consider maxPages for large datasets
  • inf-page-params
    — 始终提供getNextPageParam
  • inf-loading-guards
    — 在获取更多数据前检查isFetchingNextPage
  • inf-max-pages
    — 针对大型数据集考虑设置maxPages

SSR Integration (Prefix:
ssr-
)

SSR集成(前缀:
ssr-

  • ssr-dehydration
    — Use dehydrate/hydrate pattern for SSR
  • ssr-client-per-request
    — Create QueryClient per request
  • ssr-stale-time-server
    — Set higher staleTime on server
  • ssr-hydration-boundary
    — Wrap with HydrationBoundary
  • ssr-dehydration
    — 使用dehydrate/hydrate模式实现SSR
  • ssr-client-per-request
    — 为每个请求创建QueryClient
  • ssr-stale-time-server
    — 在服务端设置更长的staleTime
  • ssr-hydration-boundary
    — 使用HydrationBoundary进行包裹

Parallel Queries (Prefix:
parallel-
)

并行查询(前缀:
parallel-

  • parallel-use-queries
    — Use useQueries for dynamic parallel queries
  • query-cancellation
    — Implement query cancellation properly
  • parallel-use-queries
    — 使用useQueries实现动态并行查询
  • query-cancellation
    — 正确实现查询取消逻辑

Performance (Prefix:
perf-
)

性能优化(前缀:
perf-

  • perf-select-transform
    — Use select to transform/filter data
  • perf-structural-sharing
    — Leverage structural sharing
  • perf-notify-change-props
    — Limit re-renders with notifyOnChangeProps
  • perf-placeholder-data
    — Use placeholderData for instant UI
  • perf-select-transform
    — 使用select进行数据转换/筛选
  • perf-structural-sharing
    — 利用结构共享特性
  • perf-notify-change-props
    — 通过notifyOnChangeProps限制重渲染
  • perf-placeholder-data
    — 使用placeholderData实现即时UI

Offline Support (Prefix:
offline-
)

离线支持(前缀:
offline-

  • network-mode
    — Configure network mode for offline support
  • persist-queries
    — Configure query persistence for offline support
  • network-mode
    — 配置网络模式以支持离线功能
  • persist-queries
    — 配置查询持久化以支持离线功能

How to Use

使用方法

Each rule file in the
rules/
directory contains:
  1. Explanation — Why this pattern matters
  2. Bad Example — Anti-pattern to avoid
  3. Good Example — Recommended implementation
  4. Context — When to apply or skip this rule
rules/
目录下的每个规则文件包含:
  1. 说明 — 该模式的重要性
  2. 反面示例 — 需要避免的反模式
  3. 正确示例 — 推荐的实现方式
  4. 适用场景 — 何时应用或跳过该规则

Full Reference

完整参考

See individual rule files in
rules/
directory for detailed guidance and code examples.
请查看
rules/
目录下的单个规则文件,获取详细指导及代码示例。