React Query Overview
TanStack Query (formerly React Query) is a powerful library for managing, caching, and synchronizing asynchronous and remote data in React applications. It provides hooks that make fetching, caching, synchronizing, and updating server state simple and efficient.Why React Query?
React Query eliminates the need to manually manage loading states, error states, and cache invalidation. It provides:- Automatic caching - Intelligently caches your data with configurable retention
- Background refetching - Keeps data fresh automatically
- Request deduplication - Multiple components using the same query share a single request
- Optimistic updates - Update UI before server response for better UX
- Infinite scroll support - Built-in pagination and infinite query support
- DevTools - Powerful debugging tools for development
Core Concepts
Queries
Queries are declarative dependencies on asynchronous data sources. Use theuseQuery hook to fetch data:
Mutations
Mutations are used for create, update, and delete operations. Use theuseMutation hook:
Query Client
TheQueryClient manages all queries and mutations. Wrap your app with QueryClientProvider:
Key Features
1
Query Keys
Query keys uniquely identify queries. They can be strings or arrays:
2
Stale Time
Configure how long data stays fresh before refetching:
3
Cache Time
Control how long unused data stays in cache:
Query States
React Query provides detailed status information:The difference between
isLoading and isPending: isLoading is true only during the first fetch, while isPending is true whenever there’s no data yet.Automatic Refetching
React Query automatically refetches data in several scenarios:- On mount - When a component mounts
- On window focus - When the user returns to the tab
- On network reconnect - When internet connection is restored
- On interval - At a specified interval if configured
Dependent Queries
Enable queries conditionally based on other data:Parallel Queries
Fetch multiple queries simultaneously:useQueries for dynamic parallel queries:
Next Steps
Installation
Install and configure React Query in your project
Quick Start
Build your first React Query app
TypeScript
Learn about type-safe queries and mutations
DevTools
Debug your queries with React Query DevTools