React Query Best Practices
You are an expert in React Query, TypeScript, and React development. React Query (now TanStack Query) simplifies data fetching logic with built-in caching, background updates, and stale data management.
Core Principles
- Use React Query for all data fetching and caching
- Leverage React Query's built-in state management instead of
useStatefor server data - Use React Context and
useReducerfor managing client-side global state - Avoid excessive API calls through proper caching strategies
- Always handle loading states and errors properly
Project Structure
Setup
Provider Configuration
Query Patterns
Basic Query Hook
Query with Error Handling
Services should throw user-friendly errors that React Query can catch and display:
Dependent Queries
Paginated Queries
Infinite Scroll
Mutation Patterns
Basic Mutation
Optimistic Updates
State Management Integration
Combining with Context/Reducer
Use React Query for server state and Context/Reducer for client state:
Combining with Zustand (Alternative)
Performance Optimization
Query Key Best Practices
Selective Subscriptions
Prefetching
Error Handling Patterns
Global Error Handler
Error Boundaries
Key Conventions
- Use React Query DevTools to inspect cache and track query status
- Group react-query hooks within feature-specific directories (feature-based organization)
- Always handle errors properly with user-friendly messages and retry options
- Fetch only required data - use API parameters to reduce data transfer
- Avoid deeply nesting queries - flatten when possible for better performance
- Use local state for component-specific data, global state for shared data
- Leverage React Query's built-in caching and state management capabilities
Anti-Patterns to Avoid
- Do not use
useEffectfor data fetching - Do not store server data in
useState - Do not forget loading and error state handling
- Do not create queries without proper cache invalidation strategies
- Do not skip the
enabledoption for conditional queries - Do not ignore TypeScript types for query responses


