react-query-best-practices
Original:🇺🇸 English
Translated
React Query v4 (TanStack Query) best practices, patterns, and troubleshooting. Use when working with useQuery, useMutation, query invalidation, caching, WebSocket integration, or any async state management in React. Based on TkDodo's comprehensive blog series.
1installs
Sourcearraydude/agent-skills
Added on
NPX Install
npx skill4agent add arraydude/agent-skills react-query-best-practicesTags
Translated version includes tags in frontmatterSKILL.md Content
View Translation Comparison →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 | |
| 2 | Mutations & Updates | CRITICAL | |
| 3 | Caching Strategy | HIGH | |
| 4 | WebSocket Integration | HIGH | |
| 5 | TypeScript Integration | MEDIUM | |
| 6 | Testing Patterns | MEDIUM | |
| 7 | Common Pitfalls | MEDIUM | |
| 8 | Migration to v5 | HIGH | |
Quick Reference
1. Query Keys & Patterns (CRITICAL)
- - Include all queryFn params in queryKey
query-keys-as-dependencies - - Use factory pattern for consistent key generation
query-key-factory - - Use select option for data transformations
query-select-transforms - - Check data first, then error, then loading
query-status-check-order - - Only destructure properties you use
query-tracked-properties - - Know when to use each approach
query-placeholder-vs-initial - - Use enabled option for dependent queries
query-dependent-enabled
2. Mutations & Updates (CRITICAL)
- - Use mutate() with callbacks over mutateAsync()
mutation-prefer-mutate - - Invalidate queries after mutations
mutation-invalidation - - Update cache directly when appropriate
mutation-direct-cache-update - - Show success immediately, rollback on failure
mutation-optimistic-updates - - Query logic in hook, UI effects in component
mutation-callback-separation
3. Caching Strategy (HIGH)
- - Set appropriate staleTime for your domain
cache-stale-time - - Keep refetch triggers enabled in production
cache-refetch-triggers
4. WebSocket Integration (HIGH)
- - Use events to trigger invalidation
websocket-event-invalidation - - Set staleTime: Infinity for WS-managed data
websocket-stale-time-infinity - - Invalidate stale queries on reconnect
websocket-reconnection
5. TypeScript Integration (MEDIUM)
- - Let TypeScript infer, type the queryFn
typescript-infer-dont-specify - - Use Zod for runtime validation
typescript-zod-validation
6. Testing Patterns (MEDIUM)
- - Create fresh QueryClient per test
testing-fresh-client - - Use MSW for network mocking
testing-msw-mocking
7. Common Pitfalls (MEDIUM)
- - Never copy query data to local state
troubleshoot-copy-to-state - - Include all dependencies in query key
troubleshoot-missing-key-deps - - Handle HTTP errors with fetch
troubleshoot-fetch-not-reject
8. Migration to v5 (HIGH)
- - cacheTime renamed to gcTime
migration-cache-time-to-gc-time - - onSuccess/onError/onSettled removed from useQuery
migration-query-callbacks-removed - - New useSuspenseQuery, useSuspenseInfiniteQuery hooks
migration-suspense-hooks
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.mdEach 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