TanStack React Query Best Practices
Treat server data as cache-backed asynchronous state with an explicit owner, identity, and view boundary; the outcome is reliable loading and error handling plus focused updates after writes.
Library Sources
- GitHub repository ID:
TanStack/query - Context7 library ID:
/tanstack/query - DeepWiki repository ID:
TanStack/query
Use Context7 for current documentation and DeepWiki for implementation details.
References
Read the references that apply to the current task before writing or reviewing TanStack Query code.
- Let TanStack Query own server-request lifecycle and cache identity.
- Let TanStack Query own request lifecycle rather than duplicating it with effects and local state.
- Put every response-changing request input in cache identity so distinct results never reuse one entry.
- Read request inputs exclusively from the query function's context argument, never from captured request variables.
- Preserve absent identifiers and disable the request instead of fabricating a record key.
- Partition visibility-sensitive cached data by actor identity without exposing credentials in keys.
- Resolve query status before presentation consumes data.
- Resolve query status at a Loader and Inner boundary, keeping presentation free of optional data and transport state.
- Publish query identity through loader prop contracts while resolved components receive non-null data.
- Destructure only consumed query fields so dependencies and props express semantic needs.
- Keep mutation data, callbacks, and cache updates scoped to each operation.
- Consume named mutation result fields because the complete
useMutationresult is not referentially stable. - Pass changing operation input through mutation variables, not a mutation hook's construction closure.
- Parse user-controlled values before mutation invocation.
- Separate mutation callback lifecycles by putting every-invocation policy in the definition and mounted UI consequences at the call site instead of aggregate-status effects.
- Invalidate the narrow stale entry identified by successful variables.
- Consume named mutation result fields because the complete