tanstack-query

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

TanStack Query Best Practices

TanStack Query 最佳实践

Comprehensive performance optimization guide for TanStack Query v5 applications. Contains 40 rules across 8 categories, prioritized by impact to guide automated refactoring and code generation.
针对TanStack Query v5应用的全面性能优化指南。包含8个类别共40条规则,按影响优先级排序,可指导自动化重构和代码生成。

When to Apply

适用场景

Reference these guidelines when:
  • Writing new queries, mutations, or data fetching logic
  • Implementing caching strategies (staleTime, gcTime)
  • Reviewing code for performance issues or request waterfalls
  • Refactoring existing TanStack Query code
  • Implementing infinite queries, Suspense, or optimistic updates
在以下场景中参考这些指南:
  • 编写新的查询、Mutations或数据获取逻辑
  • 实现缓存策略(staleTime、gcTime)
  • 审查代码以排查性能问题或请求瀑布
  • 重构现有TanStack Query代码
  • 实现无限查询、Suspense或乐观更新

Rule Categories by Priority

按优先级划分的规则类别

PriorityCategoryImpactPrefix
1Query Key StructureCRITICAL
tquery-
2Caching ConfigurationCRITICAL
cache-
3Mutation PatternsHIGH
mutation-
4Prefetching & WaterfallsHIGH
prefetch-
5Infinite QueriesMEDIUM
infinite-
6Suspense IntegrationMEDIUM
suspense-
7Error & Retry HandlingMEDIUM
error-
8Render OptimizationLOW-MEDIUM
render-
优先级类别影响程度前缀
1查询键结构关键
tquery-
2缓存配置关键
cache-
3Mutation模式
mutation-
4预取与请求瀑布
prefetch-
5无限查询
infinite-
6Suspense集成
suspense-
7错误与重试处理
error-
8渲染优化低-中
render-

Quick Reference

快速参考

1. Query Key Structure (CRITICAL)

1. 查询键结构(关键)

  • tquery-key-factories
    - Use centralized query key factories
  • tquery-hierarchical-keys
    - Structure keys from generic to specific
  • tquery-always-arrays
    - Always use array query keys
  • tquery-serializable-objects
    - Use serializable objects in keys
  • tquery-options-pattern
    - Use queryOptions for type-safe sharing
  • tquery-colocate-keys
    - Colocate query keys with features
  • tquery-key-factories
    - 使用集中式查询键工厂
  • tquery-hierarchical-keys
    - 按从通用到具体的结构组织键
  • tquery-always-arrays
    - 始终使用数组形式的查询键
  • tquery-serializable-objects
    - 在键中使用可序列化对象
  • tquery-options-pattern
    - 使用queryOptions实现类型安全的共享
  • tquery-colocate-keys
    - 将查询键与功能代码放在一起

2. Caching Configuration (CRITICAL)

2. 缓存配置(关键)

  • cache-staletime-gctime
    - Understand staleTime vs gcTime
  • cache-global-defaults
    - Configure global defaults appropriately
  • cache-placeholder-vs-initial
    - Use placeholderData vs initialData correctly
  • cache-invalidation-precision
    - Invalidate with precision
  • cache-refetch-triggers
    - Control automatic refetch triggers
  • cache-enabled-option
    - Use enabled for conditional queries
  • cache-staletime-gctime
    - 理解staleTime与gcTime的区别
  • cache-global-defaults
    - 合理配置全局默认值
  • cache-placeholder-vs-initial
    - 正确使用placeholderData和initialData
  • cache-invalidation-precision
    - 精准地使缓存失效
  • cache-refetch-triggers
    - 控制自动重新获取的触发条件
  • cache-enabled-option
    - 使用enabled实现条件查询

3. Mutation Patterns (HIGH)

3. Mutation模式(高)

  • mutation-optimistic-updates
    - Implement optimistic updates with rollback
  • mutation-invalidate-onsettled
    - Invalidate in onSettled, not onSuccess
  • mutation-cancel-queries
    - Cancel queries before optimistic updates
  • mutation-setquerydata
    - Use setQueryData for immediate cache updates
  • mutation-avoid-parallel
    - Avoid parallel mutations on same data
  • mutation-optimistic-updates
    - 实现带回滚的乐观更新
  • mutation-invalidate-onsettled
    - 在onSettled中使缓存失效,而非onSuccess
  • mutation-cancel-queries
    - 在乐观更新前取消查询
  • mutation-setquerydata
    - 使用setQueryData实现即时缓存更新
  • mutation-avoid-parallel
    - 避免对同一数据执行并行Mutations

4. Prefetching & Waterfalls (HIGH)

4. 预取与请求瀑布(高)

  • prefetch-avoid-waterfalls
    - Avoid request waterfalls
  • prefetch-on-hover
    - Prefetch on hover for perceived speed
  • prefetch-in-queryfn
    - Prefetch dependent data in queryFn
  • prefetch-server-components
    - Prefetch in Server Components
  • prefetch-flatten-api
    - Flatten API to reduce waterfalls
  • prefetch-avoid-waterfalls
    - 避免请求瀑布
  • prefetch-on-hover
    - 在悬停时预取以提升感知速度
  • prefetch-in-queryfn
    - 在queryFn中预取依赖数据
  • prefetch-server-components
    - 在Server Components中预取
  • prefetch-flatten-api
    - 扁平化API以减少请求瀑布

5. Infinite Queries (MEDIUM)

5. 无限查询(中)

  • infinite-max-pages
    - Limit infinite query pages with maxPages
  • infinite-flatten-pages
    - Flatten pages for rendering
  • infinite-refetch-behavior
    - Understand infinite query refetch behavior
  • infinite-loading-states
    - Handle infinite query loading states correctly
  • infinite-max-pages
    - 使用maxPages限制无限查询的页数
  • infinite-flatten-pages
    - 扁平化页面数据以用于渲染
  • infinite-refetch-behavior
    - 理解无限查询的重新获取行为
  • infinite-loading-states
    - 正确处理无限查询的加载状态

6. Suspense Integration (MEDIUM)

6. Suspense集成(中)

  • suspense-use-suspense-hooks
    - Use Suspense hooks for simpler loading states
  • suspense-error-boundaries
    - Always pair Suspense with Error Boundaries
  • suspense-parallel-queries
    - Combine Suspense queries with useSuspenseQueries
  • suspense-boundaries-placement
    - Place Suspense boundaries strategically
  • suspense-use-suspense-hooks
    - 使用Suspense钩子简化加载状态处理
  • suspense-error-boundaries
    - 始终将Suspense与Error Boundaries配合使用
  • suspense-parallel-queries
    - 使用useSuspenseQueries组合Suspense查询
  • suspense-boundaries-placement
    - 合理放置Suspense边界

7. Error & Retry Handling (MEDIUM)

7. 错误与重试处理(中)

  • error-retry-config
    - Configure retry with exponential backoff
  • error-conditional-retry
    - Use conditional retry based on error type
  • error-global-handler
    - Use global error handler for common errors
  • error-display-patterns
    - Display errors appropriately
  • error-throw-on-error
    - Use throwOnError with Error Boundaries
  • error-retry-config
    - 配置带指数退避的重试机制
  • error-conditional-retry
    - 根据错误类型实现条件重试
  • error-global-handler
    - 使用全局错误处理程序处理常见错误
  • error-display-patterns
    - 合理展示错误信息
  • error-throw-on-error
    - 将throwOnError与Error Boundaries配合使用

8. Render Optimization (LOW-MEDIUM)

8. 渲染优化(低-中)

  • render-select-memoize
    - Memoize select functions
  • render-select-derived
    - Use select to derive data and reduce re-renders
  • render-notify-props
    - Use notifyOnChangeProps to limit re-renders
  • render-structural-sharing
    - Understand structural sharing
  • render-tracked-props
    - Avoid destructuring all properties
  • render-select-memoize
    - 对select函数进行记忆化处理
  • render-select-derived
    - 使用select派生数据以减少重渲染
  • render-notify-props
    - 使用notifyOnChangeProps限制重渲染
  • render-structural-sharing
    - 理解结构共享机制
  • render-tracked-props
    - 避免解构所有属性

How to Use

使用方法

Read individual reference files for detailed explanations and code examples:
  • Section definitions - Category structure and impact levels
  • Reference files:
    references/{prefix}-{slug}.md
Each reference file contains:
  • Brief explanation of why it matters
  • Incorrect code example with explanation
  • Correct code example with explanation
  • Additional context and references
阅读各个参考文件以获取详细说明和代码示例:
  • 章节定义 - 类别结构和影响级别
  • 参考文件:
    references/{prefix}-{slug}.md
每个参考文件包含:
  • 简要说明其重要性
  • 错误代码示例及解释
  • 正确代码示例及解释
  • 额外背景信息和参考资料

Related Skills

相关技能

  • For generating type-safe query hooks, see
    orval
    skill
  • For mocking API responses in tests, see
    test-msw
    skill
  • For React 19 data fetching patterns, see
    react-19
    skill
  • 如需生成类型安全的查询钩子,请查看
    orval
    技能
  • 如需在测试中模拟API响应,请查看
    test-msw
    技能
  • 如需了解React 19数据获取模式,请查看
    react-19
    技能

Full Compiled Document

完整编译文档

For the complete guide with all rules expanded:
AGENTS.md
如需查看包含所有展开规则的完整指南:
AGENTS.md