react-query-best-practices
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseReact 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
按优先级排序的规则类别
| Priority | Category | Impact | Prefix |
|---|---|---|---|
| 1 | Query Keys & Patterns | CRITICAL | |
| 2 | Mutations & Updates | CRITICAL | |
| 3 | Caching Strategy | HIGH | |
| 4 | WebSocket Integration | HIGH | |
| 5 | TypeScript Integration | MEDIUM | |
| 6 | Testing Patterns | MEDIUM | |
| 7 | Common Pitfalls | MEDIUM | |
| 8 | Migration to v5 | HIGH | |
| 优先级 | 类别 | 影响程度 | 前缀 |
|---|---|---|---|
| 1 | Query Keys & Patterns | 关键 | |
| 2 | Mutations & Updates | 关键 | |
| 3 | Caching Strategy | 高 | |
| 4 | WebSocket Integration | 高 | |
| 5 | TypeScript Integration | 中 | |
| 6 | Testing Patterns | 中 | |
| 7 | Common Pitfalls | 中 | |
| 8 | Migration to v5 | 高 | |
Quick Reference
快速参考
1. Query Keys & Patterns (CRITICAL)
1. Query Keys & Patterns(关键)
- - Include all queryFn params in queryKey
query-keys-as-dependencies - - Use factory pattern for consistent key generation
query-key-factory - - Use select option for data transformations
query-select-transforms - - Check data first, then error, then loading
query-status-check-order - - Only destructure properties you use
query-tracked-properties - - Know when to use each approach
query-placeholder-vs-initial - - Use enabled option for dependent queries
query-dependent-enabled
- - 将所有queryFn参数包含在queryKey中
query-keys-as-dependencies - - 使用工厂模式生成一致的key
query-key-factory - - 使用select选项进行数据转换
query-select-transforms - - 先检查数据,再检查错误,最后检查加载状态
query-status-check-order - - 仅解构你实际使用的属性
query-tracked-properties - - 了解何时使用每种方式
query-placeholder-vs-initial - - 对依赖查询使用enabled选项
query-dependent-enabled
2. Mutations & Updates (CRITICAL)
2. Mutations & Updates(关键)
- - Use mutate() with callbacks over mutateAsync()
mutation-prefer-mutate - - Invalidate queries after mutations
mutation-invalidation - - Update cache directly when appropriate
mutation-direct-cache-update - - Show success immediately, rollback on failure
mutation-optimistic-updates - - Query logic in hook, UI effects in component
mutation-callback-separation
- - 优先使用带回调的mutate()而非mutateAsync()
mutation-prefer-mutate - - mutation后使查询失效
mutation-invalidation - - 在合适的情况下直接更新缓存
mutation-direct-cache-update - - 立即展示成功状态,失败时回滚
mutation-optimistic-updates - - 查询逻辑放在hook中,UI效果放在组件中
mutation-callback-separation
3. Caching Strategy (HIGH)
3. Caching Strategy(高)
- - Set appropriate staleTime for your domain
cache-stale-time - - Keep refetch triggers enabled in production
cache-refetch-triggers
- - 为你的业务域设置合适的staleTime
cache-stale-time - - 在生产环境中保持重新获取触发器启用
cache-refetch-triggers
4. WebSocket Integration (HIGH)
4. WebSocket Integration(高)
- - Use events to trigger invalidation
websocket-event-invalidation - - Set staleTime: Infinity for WS-managed data
websocket-stale-time-infinity - - Invalidate stale queries on reconnect
websocket-reconnection
- - 使用事件触发失效
websocket-event-invalidation - - 为WebSocket管理的数据设置staleTime: Infinity
websocket-stale-time-infinity - - 重新连接时使过期查询失效
websocket-reconnection
5. TypeScript Integration (MEDIUM)
5. TypeScript Integration(中)
- - Let TypeScript infer, type the queryFn
typescript-infer-dont-specify - - Use Zod for runtime validation
typescript-zod-validation
- - 让TypeScript自动推断,为queryFn添加类型
typescript-infer-dont-specify - - 使用Zod进行运行时验证
typescript-zod-validation
6. Testing Patterns (MEDIUM)
6. Testing Patterns(中)
- - Create fresh QueryClient per test
testing-fresh-client - - Use MSW for network mocking
testing-msw-mocking
- - 每个测试创建新的QueryClient
testing-fresh-client - - 使用MSW进行网络模拟
testing-msw-mocking
7. Common Pitfalls (MEDIUM)
7. Common Pitfalls(中)
- - Never copy query data to local state
troubleshoot-copy-to-state - - Include all dependencies in query key
troubleshoot-missing-key-deps - - Handle HTTP errors with fetch
troubleshoot-fetch-not-reject
- - 切勿将查询数据复制到本地状态
troubleshoot-copy-to-state - - 将所有依赖项包含在query key中
troubleshoot-missing-key-deps - - 使用fetch处理HTTP错误
troubleshoot-fetch-not-reject
8. Migration to v5 (HIGH)
8. Migration to v5(高)
- - cacheTime renamed to gcTime
migration-cache-time-to-gc-time - - onSuccess/onError/onSettled removed from useQuery
migration-query-callbacks-removed - - New useSuspenseQuery, useSuspenseInfiniteQuery hooks
migration-suspense-hooks
- - cacheTime重命名为gcTime
migration-cache-time-to-gc-time - - onSuccess/onError/onSettled从useQuery中移除
migration-query-callbacks-removed - - 新增useSuspenseQuery、useSuspenseInfiniteQuery hooks
migration-suspense-hooks
Core Mental Model
核心思维模型
- React Query is NOT a data fetching library - it's an async state manager
- Server state != Client state - never mix them in global state managers
- Stale-while-revalidate - show cached data immediately, fetch in background
- Query keys are dependencies - include all variables used in queryFn
- React Query 不是数据获取库 - 它是一个异步状态管理器
- 服务端状态 ≠ 客户端状态 - 切勿在全局状态管理器中混合使用两者
- Stale-while-revalidate(失效时重新验证) - 立即展示缓存数据,在后台进行获取
- 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.mdEach 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