TanStack Query for React provides powerful hooks for fetching, caching, and updating asynchronous data in your React applications.
Installation
Setup
Wrap your application with QueryClientProvider:
Core Hooks
useQuery
Fetch and cache data with the useQuery hook:
useMutation
Perform side effects with the useMutation hook:
useInfiniteQuery
Implement infinite scrolling or pagination:
Suspense Support
useSuspenseQuery
React Query has first-class support for React Suspense:
useSuspenseQuery automatically sets enabled: true and suspense: true. The query will never return isLoading - it will suspend instead.
useSuspenseInfiniteQuery
Combine Suspense with infinite queries:
Advanced Patterns
useQueries
Execute multiple queries in parallel:
Query Options Factory
Create reusable query configurations:
Error Boundaries
Handle errors with React Error Boundaries:
Hydration
For SSR frameworks like Next.js:
TypeScript
Full TypeScript support with type inference:
React-Specific Features
Automatic Request Cancellation
React Query automatically cancels outgoing requests when components unmount:
The signal parameter in queryFn is automatically provided and will abort the request if the component unmounts or the query is cancelled.
Window Focus Refetching
Queries automatically refetch when the window regains focus:
useMutationState
Access the state of all mutations:
Structural Sharing
React Query automatically uses structural sharing to minimize re-renders:
Transform data without causing unnecessary re-renders: