tanstack-query

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

TanStack Query

TanStack Query

Overview

概述

TanStack Query is an async state manager, not a data fetching library. You provide a
queryFn
that returns a Promise; React Query handles caching, deduplication, background updates, and stale data management.
When 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的
queryFn
,React Query会处理缓存、请求去重、后台更新以及过期数据管理。
适用场景:无限滚动、离线优先应用、聚焦/重连时自动重新获取、复杂缓存失效、React Native、混合服务端/客户端应用。
不适用场景:纯同步状态(使用useState/Zustand)、规范化GraphQL缓存(Apollo/urql)、仅服务端组件应用(原生fetch)、简单的获取并展示(服务端组件)。

Quick Reference

快速参考

PatternAPIKey Points
Basic query
useQuery({ queryKey, queryFn })
Include params in queryKey
Suspense query
useSuspenseQuery(options)
No
enabled
option allowed
Parallel queries
useQueries({ queries, combine })
Dynamic parallel fetching
Dependent query
useQuery({ enabled: !!dep })
Wait for prerequisite data
Query options
queryOptions({ queryKey, queryFn })
Reusable, type-safe config
Basic mutation
useMutation({ mutationFn, onSuccess })
Invalidate on success
Mutation state
useMutationState({ filters, select })
Cross-component mutation tracking
Optimistic update
onMutate
-> cancel -> snapshot -> set
Rollback in
onError
Infinite query
useInfiniteQuery({ initialPageParam })
initialPageParam
required in v5
Prefetch
queryClient.prefetchQuery(options)
Preload on hover/intent
Invalidation
queryClient.invalidateQueries({ queryKey })
Fuzzy-matches by default, active only
Cancellation
queryFn: ({ signal }) => fetch(url, { signal })
Auto-cancel on key change
Select transform
select: (data) => data.filter(...)
Structural sharing preserved
Skip token
queryFn: id ? () => fetch(id) : skipToken
Type-safe conditional disabling
Serial mutations
useMutation({ scope: { id } })
Same scope ID runs mutations in serial
模式API核心要点
基础查询
useQuery({ queryKey, queryFn })
将参数包含在queryKey中
Suspense查询
useSuspenseQuery(options)
不允许使用
enabled
选项
并行查询
useQueries({ queries, combine })
动态并行获取
依赖查询
useQuery({ enabled: !!dep })
等待前置数据加载完成
查询选项
queryOptions({ queryKey, queryFn })
可复用、类型安全的配置
基础变更
useMutation({ mutationFn, onSuccess })
成功时使缓存失效
变更状态
useMutationState({ filters, select })
跨组件变更状态追踪
乐观更新
onMutate
-> cancel -> snapshot -> set
onError
中回滚
无限查询
useInfiniteQuery({ initialPageParam })
v5中必须指定
initialPageParam
预获取
queryClient.prefetchQuery(options)
在 hover/用户意图触发时预加载
缓存失效
queryClient.invalidateQueries({ queryKey })
默认模糊匹配,仅对活跃查询生效
请求取消
queryFn: ({ signal }) => fetch(url, { signal })
当queryKey变化时自动取消
选择转换
select: (data) => data.filter(...)
保留结构共享
跳过令牌
queryFn: id ? () => fetch(id) : skipToken
类型安全的条件禁用
串行变更
useMutation({ scope: { id } })
相同scope ID的变更会串行执行

v5 Migration Quick Reference

v5迁移快速参考

v4 (Removed)v5 (Use Instead)
useQuery(key, fn, opts)
useQuery({ queryKey, queryFn, ...opts })
cacheTime
gcTime
isLoading
(no data)
isPending
keepPreviousData: true
placeholderData: keepPreviousData
onSuccess/onError
on queries
useEffect
or mutation callbacks
useErrorBoundary
throwOnError
No
initialPageParam
initialPageParam
required
Error type
unknown
Error type defaults to
Error
v4(已移除)v5(替代方案)
useQuery(key, fn, opts)
useQuery({ queryKey, queryFn, ...opts })
cacheTime
gcTime
isLoading
(无数据时)
isPending
keepPreviousData: true
placeholderData: keepPreviousData
查询中的
onSuccess/onError
useEffect
或变更回调函数
useErrorBoundary
throwOnError
initialPageParam
必须指定
initialPageParam
错误类型
unknown
错误类型默认改为
Error

Common Mistakes

常见错误

MistakeCorrect Pattern
Checking
isPending
before
data
Data-first: check
data
->
error
->
isPending
Copying server state to local useStateUse data directly or derived state pattern
Creating QueryClient in componentCreate once outside component or in useState
Using
refetch()
for parameter changes
Include params in queryKey, let it refetch automatically
Same key for useQuery and useInfiniteQueryUse distinct key segments (different cache structures)
Inline select without memoizationExtract to stable function or useCallback
Using
catch
without re-throwing
Throw errors in queryFn (fetch doesn't reject on 4xx/5xx)
Manual generics on useQueryType the queryFn return, let inference work
Destructuring query for type narrowingKeep query object intact for proper narrowing
Using
enabled
with
useSuspenseQuery
Use conditional rendering to mount/unmount component
Not awaiting prefetch for SSRAwait
prefetchQuery
to avoid hydration mismatches
invalidateQueries
not refetching all
Use
refetchType: 'all'
for inactive queries
错误做法正确实践
在检查
data
之前先判断
isPending
数据优先:先检查
data
->
error
->
isPending
将服务端状态复制到本地useState中直接使用数据或派生状态模式
在组件内部创建QueryClient在组件外部创建一次,或使用useState创建
使用
refetch()
来响应参数变化
将参数包含在queryKey中,让其自动重新获取
useQuery和useInfiniteQuery使用相同的key使用不同的key段(缓存结构不同)
未记忆化的内联select函数提取为稳定函数或使用useCallback
使用
catch
但不重新抛出错误
在queryFn中抛出错误(fetch不会在4xx/5xx状态码时reject)
在useQuery上手动指定泛型为queryFn的返回值指定类型,让类型推断自动工作
解构query对象以缩小类型范围保持query对象完整以实现正确的类型缩小
useSuspenseQuery
中使用
enabled
使用条件渲染来挂载/卸载组件
SSR时不等待预获取完成等待
prefetchQuery
完成以避免水合不匹配
invalidateQueries
未重新获取所有查询
对非活跃查询使用
refetchType: 'all'

Delegation

任务委托

  • Query pattern discovery: Use
    Explore
    agent
  • Cache strategy review: Use
    Task
    agent
  • Code review: Delegate to
    code-reviewer
    agent
  • 查询模式发现:使用
    Explore
    agent
  • 缓存策略评审:使用
    Task
    agent
  • 代码评审:委托给
    code-reviewer
    agent

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缓存、协调配置