TanStack Query (React Query)
Best practices for managing server state in React applications using TanStack Query v5.
Core Concepts
- •QueryClient: The central cache manager.
- •useQuery: Fetching data with automatic caching and background updates.
- •useMutation: Performing side effects (POST/PUT/DELETE) and updating the cache.
- •Query Keys: Structured keys (e.g.,
['users', id]) for precise cache control.
Best Practices
- •Invalidation: Always use
queryClient.invalidateQueriesafter mutations to keep data fresh. - •Error Handling: Use
onErroror global error boundaries for consistent UX. - •Optimistic Updates: Implement UI changes before server confirmation for a "snappy" feel.
- •Prefetching: Load data before the user needs it (e.g., on hover).
When to Apply
- •Creating new data hooks.
- •Handling paginated or infinite loading lists.
- •Managing complex form submissions with server feedback.
- •Optimizing network performance via caching.