react-query-best-practices

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

React Query Best Practices

React Query 最佳实践

Important: This guide targets React Query v4. Some patterns may differ in v5.
Comprehensive guide for React Query v4 (TanStack Query) based on TkDodo's authoritative blog series. Contains 24 rules across 7 categories, prioritized by impact.
重要提示:本指南针对React Query v4。部分模式在v5中可能有所不同。
这是基于TkDodo权威博客系列打造的React Query v4(TanStack Query)全面指南,包含7个类别共24条规则,按影响程度排序。

When to Apply

适用场景

Reference these guidelines when:
  • Implementing new queries or mutations
  • Integrating WebSockets with React Query
  • Setting up query invalidation patterns
  • Debugging React Query behavior
  • Optimizing render performance
  • TypeScript integration questions
在以下场景中可参考本指南:
  • 实现新的查询或mutation
  • 为React Query集成WebSocket
  • 配置查询失效模式
  • 调试React Query行为
  • 优化渲染性能
  • 解决TypeScript集成问题

Rule Categories by Priority

按优先级排序的规则类别

PriorityCategoryImpactPrefix
1Query Keys & PatternsCRITICAL
query-
2Mutations & UpdatesCRITICAL
mutation-
3Caching StrategyHIGH
cache-
4WebSocket IntegrationHIGH
websocket-
5TypeScript IntegrationMEDIUM
typescript-
6Testing PatternsMEDIUM
testing-
7Common PitfallsMEDIUM
troubleshoot-
8Migration to v5HIGH
migration-
优先级类别影响程度前缀
1Query Keys & Patterns关键
query-
2Mutations & Updates关键
mutation-
3Caching Strategy
cache-
4WebSocket Integration
websocket-
5TypeScript Integration
typescript-
6Testing Patterns
testing-
7Common Pitfalls
troubleshoot-
8Migration to v5
migration-

Quick Reference

快速参考

1. Query Keys & Patterns (CRITICAL)

1. Query Keys & Patterns(关键)

  • query-keys-as-dependencies
    - Include all queryFn params in queryKey
  • query-key-factory
    - Use factory pattern for consistent key generation
  • query-select-transforms
    - Use select option for data transformations
  • query-status-check-order
    - Check data first, then error, then loading
  • query-tracked-properties
    - Only destructure properties you use
  • query-placeholder-vs-initial
    - Know when to use each approach
  • query-dependent-enabled
    - Use enabled option for dependent queries
  • query-keys-as-dependencies
    - 将所有queryFn参数包含在queryKey中
  • query-key-factory
    - 使用工厂模式生成一致的key
  • query-select-transforms
    - 使用select选项进行数据转换
  • query-status-check-order
    - 先检查数据,再检查错误,最后检查加载状态
  • query-tracked-properties
    - 仅解构你实际使用的属性
  • query-placeholder-vs-initial
    - 了解何时使用每种方式
  • query-dependent-enabled
    - 对依赖查询使用enabled选项

2. Mutations & Updates (CRITICAL)

2. Mutations & Updates(关键)

  • mutation-prefer-mutate
    - Use mutate() with callbacks over mutateAsync()
  • mutation-invalidation
    - Invalidate queries after mutations
  • mutation-direct-cache-update
    - Update cache directly when appropriate
  • mutation-optimistic-updates
    - Show success immediately, rollback on failure
  • mutation-callback-separation
    - Query logic in hook, UI effects in component
  • mutation-prefer-mutate
    - 优先使用带回调的mutate()而非mutateAsync()
  • mutation-invalidation
    - mutation后使查询失效
  • mutation-direct-cache-update
    - 在合适的情况下直接更新缓存
  • mutation-optimistic-updates
    - 立即展示成功状态,失败时回滚
  • mutation-callback-separation
    - 查询逻辑放在hook中,UI效果放在组件中

3. Caching Strategy (HIGH)

3. Caching Strategy(高)

  • cache-stale-time
    - Set appropriate staleTime for your domain
  • cache-refetch-triggers
    - Keep refetch triggers enabled in production
  • cache-stale-time
    - 为你的业务域设置合适的staleTime
  • cache-refetch-triggers
    - 在生产环境中保持重新获取触发器启用

4. WebSocket Integration (HIGH)

4. WebSocket Integration(高)

  • websocket-event-invalidation
    - Use events to trigger invalidation
  • websocket-stale-time-infinity
    - Set staleTime: Infinity for WS-managed data
  • websocket-reconnection
    - Invalidate stale queries on reconnect
  • websocket-event-invalidation
    - 使用事件触发失效
  • websocket-stale-time-infinity
    - 为WebSocket管理的数据设置staleTime: Infinity
  • websocket-reconnection
    - 重新连接时使过期查询失效

5. TypeScript Integration (MEDIUM)

5. TypeScript Integration(中)

  • typescript-infer-dont-specify
    - Let TypeScript infer, type the queryFn
  • typescript-zod-validation
    - Use Zod for runtime validation
  • typescript-infer-dont-specify
    - 让TypeScript自动推断,为queryFn添加类型
  • typescript-zod-validation
    - 使用Zod进行运行时验证

6. Testing Patterns (MEDIUM)

6. Testing Patterns(中)

  • testing-fresh-client
    - Create fresh QueryClient per test
  • testing-msw-mocking
    - Use MSW for network mocking
  • testing-fresh-client
    - 每个测试创建新的QueryClient
  • testing-msw-mocking
    - 使用MSW进行网络模拟

7. Common Pitfalls (MEDIUM)

7. Common Pitfalls(中)

  • troubleshoot-copy-to-state
    - Never copy query data to local state
  • troubleshoot-missing-key-deps
    - Include all dependencies in query key
  • troubleshoot-fetch-not-reject
    - Handle HTTP errors with fetch
  • troubleshoot-copy-to-state
    - 切勿将查询数据复制到本地状态
  • troubleshoot-missing-key-deps
    - 将所有依赖项包含在query key中
  • troubleshoot-fetch-not-reject
    - 使用fetch处理HTTP错误

8. Migration to v5 (HIGH)

8. Migration to v5(高)

  • migration-cache-time-to-gc-time
    - cacheTime renamed to gcTime
  • migration-query-callbacks-removed
    - onSuccess/onError/onSettled removed from useQuery
  • migration-suspense-hooks
    - New useSuspenseQuery, useSuspenseInfiniteQuery hooks
  • migration-cache-time-to-gc-time
    - cacheTime重命名为gcTime
  • migration-query-callbacks-removed
    - onSuccess/onError/onSettled从useQuery中移除
  • migration-suspense-hooks
    - 新增useSuspenseQuery、useSuspenseInfiniteQuery hooks

Core Mental Model

核心思维模型

  1. React Query is NOT a data fetching library - it's an async state manager
  2. Server state != Client state - never mix them in global state managers
  3. Stale-while-revalidate - show cached data immediately, fetch in background
  4. Query keys are dependencies - include all variables used in queryFn
  1. React Query 不是数据获取库 - 它是一个异步状态管理器
  2. 服务端状态 ≠ 客户端状态 - 切勿在全局状态管理器中混合使用两者
  3. Stale-while-revalidate(失效时重新验证) - 立即展示缓存数据,在后台进行获取
  4. Query keys 是依赖项 - 包含queryFn中使用的所有变量

How to Use

使用方法

Read individual rule files for detailed explanations and code examples:
rules/query-key-factory.md
rules/mutation-invalidation.md
rules/websocket-event-invalidation.md
Each rule file contains:
  • Brief explanation of why it matters
  • Incorrect code example
  • Correct code example
阅读单个规则文件获取详细说明及代码示例:
rules/query-key-factory.md
rules/mutation-invalidation.md
rules/websocket-event-invalidation.md
每个规则文件包含:
  • 简要说明该规则的重要性
  • 错误代码示例
  • 正确代码示例

Full Compiled Document

完整编译文档

For the complete guide with all rules expanded:
AGENTS.md
如需包含所有规则详细内容的完整指南,请查看:
AGENTS.md