tanstack-query-best-practices
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTanStack 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
按优先级划分的规则类别
| Priority | Category | Rules | Impact |
|---|---|---|---|
| CRITICAL | Query Keys | 5 rules | Prevents cache bugs and data inconsistencies |
| CRITICAL | Caching | 5 rules | Optimizes performance and data freshness |
| HIGH | Mutations | 6 rules | Ensures data integrity and UI consistency |
| HIGH | Error Handling | 3 rules | Prevents poor user experiences |
| MEDIUM | Prefetching | 4 rules | Improves perceived performance |
| MEDIUM | Parallel Queries | 2 rules | Enables dynamic parallel fetching |
| MEDIUM | Infinite Queries | 3 rules | Prevents pagination bugs |
| MEDIUM | SSR Integration | 4 rules | Enables proper hydration |
| LOW | Performance | 4 rules | Reduces unnecessary re-renders |
| LOW | Offline Support | 2 rules | Enables 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-
)
qk-- — Always use arrays for query keys
qk-array-structure - — Include all variables the query depends on
qk-include-dependencies - — Organize keys hierarchically (entity → id → filters)
qk-hierarchical-organization - — Use query key factories for complex applications
qk-factory-pattern - — Ensure all key parts are JSON-serializable
qk-serializable
- — 始终使用数组作为查询键
qk-array-structure - — 包含查询依赖的所有变量
qk-include-dependencies - — 按层级组织键(实体 → ID → 筛选条件)
qk-hierarchical-organization - — 在复杂应用中使用查询键工厂模式
qk-factory-pattern - — 确保键的所有部分均可JSON序列化
qk-serializable
Caching (Prefix: cache-
)
cache-缓存(前缀:cache-
)
cache-- — Set appropriate staleTime based on data volatility
cache-stale-time - — Configure gcTime for inactive query retention
cache-gc-time - — Set sensible defaults at QueryClient level
cache-defaults - — Use targeted invalidation over broad patterns
cache-invalidation - — Understand placeholder vs initial data differences
cache-placeholder-vs-initial
- — 根据数据波动情况设置合适的staleTime
cache-stale-time - — 配置gcTime以保留非活跃查询
cache-gc-time - — 在QueryClient层面设置合理的默认值
cache-defaults - — 使用针对性的失效策略而非宽泛模式
cache-invalidation - — 理解占位数据与初始数据的区别
cache-placeholder-vs-initial
Mutations (Prefix: mut-
)
mut-变更操作(前缀:mut-
)
mut-- — Always invalidate related queries after mutations
mut-invalidate-queries - — Implement optimistic updates for responsive UI
mut-optimistic-updates - — Provide rollback context from onMutate
mut-rollback-context - — Handle mutation errors gracefully
mut-error-handling - — Use isPending for mutation loading states
mut-loading-states - — Use useMutationState for cross-component tracking
mut-mutation-state
- — 变更后始终使相关查询失效
mut-invalidate-queries - — 实现乐观更新以获得响应式UI
mut-optimistic-updates - — 从onMutate中提供回滚上下文
mut-rollback-context - — 优雅处理变更操作错误
mut-error-handling - — 使用isPending表示变更加载状态
mut-loading-states - — 使用useMutationState实现跨组件状态追踪
mut-mutation-state
Error Handling (Prefix: err-
)
err-错误处理(前缀:err-
)
err-- — Use error boundaries with useQueryErrorResetBoundary
err-error-boundaries - — Configure retry logic appropriately
err-retry-config - — Provide fallback data when appropriate
err-fallback-data
- — 将错误边界与useQueryErrorResetBoundary结合使用
err-error-boundaries - — 合理配置重试逻辑
err-retry-config - — 适时提供降级数据
err-fallback-data
Prefetching (Prefix: pf-
)
pf-预获取(前缀:pf-
)
pf-- — Prefetch on user intent (hover, focus)
pf-intent-prefetch - — Prefetch data during route transitions
pf-route-prefetch - — Set staleTime when prefetching
pf-stale-time-config - — Use ensureQueryData for conditional prefetching
pf-ensure-query-data
- — 在用户有操作意图时(如悬停、聚焦)预获取数据
pf-intent-prefetch - — 在路由切换期间预获取数据
pf-route-prefetch - — 预获取时设置staleTime
pf-stale-time-config - — 使用ensureQueryData实现条件式预获取
pf-ensure-query-data
Infinite Queries (Prefix: inf-
)
inf-无限滚动查询(前缀:inf-
)
inf-- — Always provide getNextPageParam
inf-page-params - — Check isFetchingNextPage before fetching more
inf-loading-guards - — Consider maxPages for large datasets
inf-max-pages
- — 始终提供getNextPageParam
inf-page-params - — 在获取更多数据前检查isFetchingNextPage
inf-loading-guards - — 针对大型数据集考虑设置maxPages
inf-max-pages
SSR Integration (Prefix: ssr-
)
ssr-SSR集成(前缀:ssr-
)
ssr-- — Use dehydrate/hydrate pattern for SSR
ssr-dehydration - — Create QueryClient per request
ssr-client-per-request - — Set higher staleTime on server
ssr-stale-time-server - — Wrap with HydrationBoundary
ssr-hydration-boundary
- — 使用dehydrate/hydrate模式实现SSR
ssr-dehydration - — 为每个请求创建QueryClient
ssr-client-per-request - — 在服务端设置更长的staleTime
ssr-stale-time-server - — 使用HydrationBoundary进行包裹
ssr-hydration-boundary
Parallel Queries (Prefix: parallel-
)
parallel-并行查询(前缀:parallel-
)
parallel-- — Use useQueries for dynamic parallel queries
parallel-use-queries - — Implement query cancellation properly
query-cancellation
- — 使用useQueries实现动态并行查询
parallel-use-queries - — 正确实现查询取消逻辑
query-cancellation
Performance (Prefix: perf-
)
perf-性能优化(前缀:perf-
)
perf-- — Use select to transform/filter data
perf-select-transform - — Leverage structural sharing
perf-structural-sharing - — Limit re-renders with notifyOnChangeProps
perf-notify-change-props - — Use placeholderData for instant UI
perf-placeholder-data
- — 使用select进行数据转换/筛选
perf-select-transform - — 利用结构共享特性
perf-structural-sharing - — 通过notifyOnChangeProps限制重渲染
perf-notify-change-props - — 使用placeholderData实现即时UI
perf-placeholder-data
Offline Support (Prefix: offline-
)
offline-离线支持(前缀:offline-
)
offline-- — Configure network mode for offline support
network-mode - — Configure query persistence for offline support
persist-queries
- — 配置网络模式以支持离线功能
network-mode - — 配置查询持久化以支持离线功能
persist-queries
How to Use
使用方法
Each rule file in the directory contains:
rules/- Explanation — Why this pattern matters
- Bad Example — Anti-pattern to avoid
- Good Example — Recommended implementation
- Context — When to apply or skip this rule
rules/- 说明 — 该模式的重要性
- 反面示例 — 需要避免的反模式
- 正确示例 — 推荐的实现方式
- 适用场景 — 何时应用或跳过该规则
Full Reference
完整参考
See individual rule files in directory for detailed guidance and code examples.
rules/请查看目录下的单个规则文件,获取详细指导及代码示例。
rules/