React Query v4 (TanStack Query) best practices, patterns, and troubleshooting...
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.
Reference these guidelines when:
| Priority | Category | Impact | Prefix |
|---|---|---|---|
| 1 | Query Keys & Patterns | CRITICAL | query- |
| 2 | Mutations & Updates | CRITICAL | mutation- |
| 3 | Caching Strategy | HIGH | cache- |
| 4 | WebSocket Integration | HIGH | websocket- |
| 5 | TypeScript Integration | MEDIUM | typescript- |
| 6 | Testing Patterns | MEDIUM | testing- |
| 7 | Common Pitfalls | MEDIUM | troubleshoot- |
| 8 | Migration to v5 | HIGH | migration- |
query-keys-as-dependencies - Include all queryFn params in queryKeyquery-key-factory - Use factory pattern for consistent key generationquery-select-transforms - Use select option for data transformationsquery-status-check-order - Check data first, then error, then loadingquery-tracked-properties - Only destructure properties you usequery-placeholder-vs-initial - Know when to use each approachquery-dependent-enabled - Use enabled option for dependent queriesmutation-prefer-mutate - Use mutate() with callbacks over mutateAsync()mutation-invalidation - Invalidate queries after mutationsmutation-direct-cache-update - Update cache directly when appropriatemutation-optimistic-updates - Show success immediately, rollback on failuremutation-callback-separation - Query logic in hook, UI effects in componentcache-stale-time - Set appropriate staleTime for your domaincache-refetch-triggers - Keep refetch triggers enabled in productionwebsocket-event-invalidation - Use events to trigger invalidationwebsocket-stale-time-infinity - Set staleTime: Infinity for WS-managed datawebsocket-reconnection - Invalidate stale queries on reconnecttypescript-infer-dont-specify - Let TypeScript infer, type the queryFntypescript-zod-validation - Use Zod for runtime validationtesting-fresh-client - Create fresh QueryClient per testtesting-msw-mocking - Use MSW for network mockingtroubleshoot-copy-to-state - Never copy query data to local statetroubleshoot-missing-key-deps - Include all dependencies in query keytroubleshoot-fetch-not-reject - Handle HTTP errors with fetchmigration-cache-time-to-gc-time - cacheTime renamed to gcTimemigration-query-callbacks-removed - onSuccess/onError/onSettled removed from useQuerymigration-suspense-hooks - New useSuspenseQuery, useSuspenseInfiniteQuery hooksRead 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:
For the complete guide with all rules expanded: AGENTS.md