react-query-best-practices
React Query Best Practices
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.
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
Rule Categories by Priority
| 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- |
Quick Reference
1. Query Keys & Patterns (CRITICAL)
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 queries
2. Mutations & Updates (CRITICAL)
mutation-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 component
3. Caching Strategy (HIGH)
cache-stale-time- Set appropriate staleTime for your domaincache-refetch-triggers- Keep refetch triggers enabled in production
4. WebSocket Integration (HIGH)
websocket-event-invalidation- Use events to trigger invalidationwebsocket-stale-time-infinity- Set staleTime: Infinity for WS-managed datawebsocket-reconnection- Invalidate stale queries on reconnect
5. TypeScript Integration (MEDIUM)
typescript-infer-dont-specify- Let TypeScript infer, type the queryFntypescript-zod-validation- Use Zod for runtime validation
6. Testing Patterns (MEDIUM)
testing-fresh-client- Create fresh QueryClient per testtesting-msw-mocking- Use MSW for network mocking
7. Common Pitfalls (MEDIUM)
troubleshoot-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 fetch
8. Migration to v5 (HIGH)
migration-single-signature- All hooks now take a single object argumentmigration-status-pending- status 'loading' → 'pending'; isLoading semantics changedmigration-cache-time-to-gc-time- cacheTime renamed to gcTimemigration-keep-previous-data- keepPreviousData → placeholderData with identity fnmigration-query-callbacks-removed- onSuccess/onError/onSettled removed from useQuerymigration-suspense-hooks- New useSuspenseQuery, useSuspenseInfiniteQuery hooksmigration-throw-on-error- useErrorBoundary renamed to throwOnErrormigration-remove-method- query.remove() removed; use queryClient.removeQueries()migration-initial-page-param- initialPageParam now required for infinite queriesmigration-refetch-page-to-max-pages- refetchPage replaced by maxPagesmigration-hydration-boundary- Hydrate component renamed to HydrationBoundarymigration-refetch-interval-callback- refetchInterval callback now receives only querymigration-context-to-query-client- context prop removed; pass queryClient directlymigration-misc-breaking-changes- React 18 min, server retry=0, hashKey, isDataEqual, etc.
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
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.md
Each rule file contains:
- Brief explanation of why it matters
- Incorrect code example
- Correct code example
Full Compiled Document
For the complete guide with all rules expanded: AGENTS.md
More from arraydude/agent-skills
feature-workflow
Feature planning, specification, phased implementation, progress tracking, per-phase PRs, and archival workflow. Use when starting a new feature, creating spec documents, breaking work into phases, tracking progress, managing PRs, or archiving completed specs.
7smc-crt-analysis
Analyze any asset (stocks, crypto, forex) using Smart Money Concepts (SMC) and Candle Range Theory (CRT). Use when the user asks for technical analysis, market structure analysis, liquidity analysis, order block identification, or price action reading. Triggers include "SMC analysis", "CRT analysis", "market structure", "order blocks", "liquidity sweep", "break of structure", "change of character", "fair value gap", "imbalance", "premium/discount", "smart money", "institutional flow", "POI", "sniper entry", "turtle soup", "where is smart money", "Wyckoff", "Elliott Wave", or any request to analyze price charts using institutional order flow concepts. Also triggers when analyzing entry/exit points, stop loss placement, or identifying manipulation patterns on any timeframe.
2