tanstack-query
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTanStack Query
TanStack Query
Overview
概述
TanStack Query is an async state manager, not a data fetching library. You provide a that returns a Promise; React Query handles caching, deduplication, background updates, and stale data management.
queryFnWhen to use: Infinite scrolling, offline-first apps, auto-refetching on focus/reconnect, complex cache invalidation, React Native, hybrid server/client apps.
When NOT to use: Purely synchronous state (useState/Zustand), normalized GraphQL caching (Apollo/urql), server-components-only apps (native fetch), simple fetch-and-display (server components).
TanStack Query是一个异步状态管理器,而非数据获取库。你只需提供一个返回Promise的,React Query会处理缓存、请求去重、后台更新以及过期数据管理。
queryFn适用场景:无限滚动、离线优先应用、聚焦/重连时自动重新获取、复杂缓存失效、React Native、混合服务端/客户端应用。
不适用场景:纯同步状态(使用useState/Zustand)、规范化GraphQL缓存(Apollo/urql)、仅服务端组件应用(原生fetch)、简单的获取并展示(服务端组件)。
Quick Reference
快速参考
| Pattern | API | Key Points |
|---|---|---|
| Basic query | | Include params in queryKey |
| Suspense query | | No |
| Parallel queries | | Dynamic parallel fetching |
| Dependent query | | Wait for prerequisite data |
| Query options | | Reusable, type-safe config |
| Basic mutation | | Invalidate on success |
| Mutation state | | Cross-component mutation tracking |
| Optimistic update | | Rollback in |
| Infinite query | | |
| Prefetch | | Preload on hover/intent |
| Invalidation | | Fuzzy-matches by default, active only |
| Cancellation | | Auto-cancel on key change |
| Select transform | | Structural sharing preserved |
| Skip token | | Type-safe conditional disabling |
| Serial mutations | | Same scope ID runs mutations in serial |
| 模式 | API | 核心要点 |
|---|---|---|
| 基础查询 | | 将参数包含在queryKey中 |
| Suspense查询 | | 不允许使用 |
| 并行查询 | | 动态并行获取 |
| 依赖查询 | | 等待前置数据加载完成 |
| 查询选项 | | 可复用、类型安全的配置 |
| 基础变更 | | 成功时使缓存失效 |
| 变更状态 | | 跨组件变更状态追踪 |
| 乐观更新 | | 在 |
| 无限查询 | | v5中必须指定 |
| 预获取 | | 在 hover/用户意图触发时预加载 |
| 缓存失效 | | 默认模糊匹配,仅对活跃查询生效 |
| 请求取消 | | 当queryKey变化时自动取消 |
| 选择转换 | | 保留结构共享 |
| 跳过令牌 | | 类型安全的条件禁用 |
| 串行变更 | | 相同scope ID的变更会串行执行 |
v5 Migration Quick Reference
v5迁移快速参考
| v4 (Removed) | v5 (Use Instead) |
|---|---|
| |
| |
| |
| |
| |
| |
No | |
Error type | Error type defaults to |
| v4(已移除) | v5(替代方案) |
|---|---|
| |
| |
| |
| |
查询中的 | |
| |
无 | 必须指定 |
错误类型 | 错误类型默认改为 |
Common Mistakes
常见错误
| Mistake | Correct Pattern |
|---|---|
Checking | Data-first: check |
| Copying server state to local useState | Use data directly or derived state pattern |
| Creating QueryClient in component | Create once outside component or in useState |
Using | Include params in queryKey, let it refetch automatically |
| Same key for useQuery and useInfiniteQuery | Use distinct key segments (different cache structures) |
| Inline select without memoization | Extract to stable function or useCallback |
Using | Throw errors in queryFn (fetch doesn't reject on 4xx/5xx) |
| Manual generics on useQuery | Type the queryFn return, let inference work |
| Destructuring query for type narrowing | Keep query object intact for proper narrowing |
Using | Use conditional rendering to mount/unmount component |
| Not awaiting prefetch for SSR | Await |
| Use |
| 错误做法 | 正确实践 |
|---|---|
在检查 | 数据优先:先检查 |
| 将服务端状态复制到本地useState中 | 直接使用数据或派生状态模式 |
| 在组件内部创建QueryClient | 在组件外部创建一次,或使用useState创建 |
使用 | 将参数包含在queryKey中,让其自动重新获取 |
| useQuery和useInfiniteQuery使用相同的key | 使用不同的key段(缓存结构不同) |
| 未记忆化的内联select函数 | 提取为稳定函数或使用useCallback |
使用 | 在queryFn中抛出错误(fetch不会在4xx/5xx状态码时reject) |
| 在useQuery上手动指定泛型 | 为queryFn的返回值指定类型,让类型推断自动工作 |
| 解构query对象以缩小类型范围 | 保持query对象完整以实现正确的类型缩小 |
在 | 使用条件渲染来挂载/卸载组件 |
| SSR时不等待预获取完成 | 等待 |
| 对非活跃查询使用 |
Delegation
任务委托
- Query pattern discovery: Use agent
Explore - Cache strategy review: Use agent
Task - Code review: Delegate to agent
code-reviewer
- 查询模式发现:使用agent
Explore - 缓存策略评审:使用agent
Task - 代码评审:委托给agent
code-reviewer
References
参考资料
- Basic patterns, architecture, and query variants
- Query keys and factory patterns
- Mutations, optimistic updates, and MutationCache
- Cache operations, staleTime vs gcTime, seeding
- Data transformations and select patterns
- Performance optimization with render tracking and structural sharing
- Error handling strategies
- Infinite queries and pagination
- Offline mode and persistence
- WebSocket and real-time integration
- SSR and hydration patterns
- TypeScript patterns
- Testing with MSW and React Testing Library
- Known v5 issues and workarounds
- Caching coordination with Router — single-source caching strategy, disabling Router cache, coordinated configuration
- 基础模式、架构和查询变体
- 查询键和工厂模式
- 变更、乐观更新和MutationCache
- 缓存操作、staleTime vs gcTime、数据预填充
- 数据转换和选择模式
- 通过渲染追踪和结构共享优化性能
- 错误处理策略
- 无限查询和分页
- 离线模式和持久化
- WebSocket和实时集成
- SSR和水合模式
- TypeScript模式
- 使用MSW和React Testing Library进行测试
- 已知v5问题和解决方案
- 与Router的缓存协调 — 单一来源缓存策略、禁用Router缓存、协调配置