Intelligent Data Caching
Store previously fetched information in a centralized query cache. Reuse available data across components and reduce unnecessary network requests when cached information is sufficient.
React Query, now known as TanStack Query, simplifies the way you fetch, cache, synchronize, and update server data. Build responsive, reliable, and scalable React applications with intelligent caching, automatic background updates, and powerful asynchronous state management.
Spend less time managing complex API requests and more time creating exceptional application experiences.
npm install @tanstack/react-query
A smarter approach to fetching and managing asynchronous data in modern React applications.

React Query is a free, open-source library designed to simplify data fetching, caching, synchronization, and server state management in React applications. Now part of the TanStack ecosystem, it provides powerful utilities for handling remote data without requiring developers to maintain complicated request and caching logic manually.
Unlike traditional state management libraries that primarily manage local application state, React Query specializes in server state, including information retrieved from REST APIs, GraphQL endpoints, databases through backend services, and other asynchronous sources.
React Query uses unique query keys to identify and organize asynchronous data. When a component requests information, the library executes a query function, stores the returned data in its cache, and makes the results available to components observing the same query.
It also manages loading states, errors, retries, background refetching, and cache synchronization.
React Query works alongside React's existing state management capabilities, allowing developers to separate local interface state from remote application data.
Explore the essential features that make React Query a flexible solution for modern, API-driven React applications.
Store previously fetched information in a centralized query cache. Reuse available data across components and reduce unnecessary network requests when cached information is sufficient.
Create, update, and delete server resources using the useMutation hook. Manage submission states, handle errors, and refresh affected data after successful operations.
Access query errors, pending states, and retry controls through a consistent interface. Configure retry behavior according to the needs of individual API requests.
Develop with TypeScript-compatible hooks, configuration options, and type inference. Create more predictable application code with strongly typed query functions and responses.
Keep application data synchronized with remote sources. Configure automatic refetching when users return to a browser tab, reconnect to the internet, or mount components that observe stale queries.
Mark selected cached resources as stale whenever underlying server information changes. Targeted invalidation helps maintain consistency across related application components.
Display anticipated changes before the server confirms an operation. Improve perceived responsiveness while using rollback logic to recover from unsuccessful mutations.
Inspect query keys, cached information, mutation activity, and data freshness through dedicated developer tools.
Coordinate concurrent requests for identical query keys. Components observing the same query can share an in-flight request and access the same cached results.
Create dynamic content feeds, paginated tables, product listings, and load-more experiences with flexible query keys and infinite query functionality.
Retrieve anticipated data before users navigate to another page or component. Prefetching can reduce perceived loading times when relevant information is already cached.
Cancel unnecessary or outdated asynchronous requests using supported AbortSignal integration. Reduce unnecessary processing when application requirements change.
TanStack Query integrates with modern React frameworks, development tools, and asynchronous data sources. Its flexible architecture allows developers to use their preferred networking libraries and backend technologies.
Manage product catalogs, customer information, shopping cart data, order details, and inventory information retrieved from backend services.
Fetch analytics, reports, statistics, and management data while maintaining synchronized information across multiple dashboard components.
Manage subscription information, account settings, user permissions, project resources, and other API-driven application features.
Use React Query with React Native to manage remote data, mobile network connectivity, cached responses, and application focus behavior.
Build dynamic content feeds, user profiles, notifications, comments, and interactive content management experiences.
Retrieve account information, transaction records, and financial reports with configurable caching and synchronization policies.
Integrate React applications with headless content management systems to retrieve articles, pages, products, and dynamic website content.
Organize complex server state across large React projects using reusable queries, consistent cache management, and configurable asynchronous workflows.
Get started with TanStack React Query through the official npm package or GitHub repository. The library is available under the MIT license and can be integrated into personal, commercial, and enterprise applications.
React Query is distributed as a JavaScript package rather than a standalone desktop installer. Developers install it directly into their React projects using a supported package manager.
Pick the package manager your project already uses and run the command in the project folder.
npm install @tanstack/react-queryyarn add @tanstack/react-querypnpm add @tanstack/react-querybun add @tanstack/react-queryExplore the source code, releases, documentation resources, and open-source contributions.
React Query GitHubThis ZIP is the source archive of react-query-kit by HuolalaTech on GitHub, a helper toolkit built on top of TanStack Query. The core React Query library installs with the package manager commands above.
Download Note: Always select a package version compatible with your React project. Review migration documentation before upgrading between major versions.
Start managing asynchronous data in your React application with a few simple configuration steps.
Ensure you have Node.js, a compatible package manager, and an existing React application.
To create a new React application using Vite, run:
npm create vite@latest my-app -- --template react
cd my-app
npm installSkip this step if you already have a compatible React project.
Open your terminal in the project directory and execute:
npm install @tanstack/react-queryThe package will be added to your project's dependencies.
Create a QueryClient instance and wrap your application with QueryClientProvider to make the query cache available throughout your component tree.
Update your main.jsx file:
import React from 'react';
import ReactDOM from 'react-dom/client';
import {
QueryClient,
QueryClientProvider
} from '@tanstack/react-query';
import App from './App.jsx';
const queryClient = new QueryClient();
ReactDOM.createRoot(
document.getElementById('root')
).render(
<QueryClientProvider client={queryClient}>
<App />
</QueryClientProvider>
);Use the useQuery hook to retrieve asynchronous data and manage loading and error states.
import { useQuery } from '@tanstack/react-query';
async function fetchUsers({ signal }) {
const response = await fetch(
'https://jsonplaceholder.typicode.com/users',
{ signal }
);
if (!response.ok) {
throw new Error('Failed to fetch users');
}
return response.json();
}
export default function App() {
const { data, isPending, isError, error } = useQuery({
queryKey: ['users'],
queryFn: fetchUsers,
staleTime: 60000
});
if (isPending) return <p>Loading users...</p>;
if (isError) return <p>{error.message}</p>;
return (
<ul>
{data.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}This example retrieves user information from a public demonstration API and caches the successful response.
Start the Vite development server:
npm run devOpen the local development URL displayed in your terminal to test the application.
Install the optional developer tools package:
npm install @tanstack/react-query-devtoolsImport the DevTools component:
import {
ReactQueryDevtools
} from '@tanstack/react-query-devtools';Add it inside QueryClientProvider:
<QueryClientProvider client={queryClient}>
<App />
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>You can now inspect cached queries and monitor asynchronous activity during development.
Explore the essential hooks and configuration options available for managing asynchronous application data.
| Hook | Functionality |
|---|---|
useQuery | Fetch and cache asynchronous data |
useMutation | Manage server-side data changes |
useInfiniteQuery | Handle infinite scrolling and incremental loading |
useQueries | Manage multiple queries |
useQueryClient | Access the shared query client |
useIsFetching | Monitor active query requests |
useIsMutating | Monitor active mutations |
useSuspenseQuery | Integrate queries with React Suspense |
useSuspenseQueries | Manage multiple Suspense queries |
useMutationState | Access matching mutation states |
| Option | Purpose |
|---|---|
staleTime | Controls how long data remains fresh |
gcTime | Controls inactive cache retention |
retry | Configures failed query retries |
enabled | Controls automatic query execution |
refetchOnWindowFocus | Controls refetching when window focus returns |
refetchOnReconnect | Controls refetching after network reconnection |
refetchInterval | Configures periodic data fetching |
placeholderData | Displays temporary data while a query resolves |
initialData | Supplies initial query cache data |
select | Transforms or selects returned data |
Query keys uniquely identify resources within the cache. Each key should describe the data being requested and include relevant variables.
Consistent query keys help prevent unrelated resources from sharing the same cache entry.
queryKey: ['products']queryKey: ['products', productId]queryKey: ['products', { category, page }]staleTime determines how long successfully fetched information is considered fresh. Its default value is zero, meaning cached data becomes stale immediately unless configured otherwise.
gcTime determines how long inactive query data remains in memory before garbage collection. The default client-side retention period is five minutes.
These settings control different aspects of cache behavior and can be configured separately.
Adjust these settings according to your application's data freshness requirements, network conditions, and expected user interactions.
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 60000,
gcTime: 300000,
retry: 2,
refetchOnWindowFocus: false
}
}
});Understand the differences between major React Query versions and discover how TanStack Query compares with other popular development libraries.
| Feature | v3 | v4 | v5 |
|---|---|---|---|
| Package | react-query | @tanstack/react-query | @tanstack/react-query |
| Branding | React Query | TanStack Query | TanStack Query |
| Hook Syntax | Multiple Signatures | Multiple Signatures | Object-Based |
| Cache Retention | cacheTime | cacheTime | gcTime |
| Pending Status | isLoading | isLoading | isPending |
| Previous Page Data | keepPreviousData Option | keepPreviousData Option | placeholderData |
| Usage | Legacy Projects | Existing Projects | Modern Projects |
Redux provides general-purpose state management, while React Query specializes in asynchronous server data.
Developers can use React Query for API responses and remote resources while retaining Redux for complex client-side application state.
Both libraries provide data fetching, caching, and background revalidation. React Query offers extensive configuration for mutations, infinite queries, cache invalidation, and asynchronous workflows.
SWR provides a concise approach to remote data fetching and revalidation.
Axios is an HTTP client used to send network requests. React Query manages request states, caching, synchronization, and asynchronous workflows.
Both technologies can be used together within the same application.
RTK Query integrates directly with Redux Toolkit. React Query provides separate server state management without requiring a Redux store.
| Library | Primary Purpose | Suitable For |
|---|---|---|
| React Query | Server State Management | API-Driven React Apps |
| Redux Toolkit | General State Management | Complex Application State |
| SWR | Data Fetching | Concise Fetching Workflows |
| RTK Query | API Data Management | Redux-Based Applications |
| Axios | HTTP Requests | Network Communication |
| Apollo Client | GraphQL Data Management | GraphQL Applications |
| Zustand | Client State Management | Lightweight Global State |
The most suitable library depends on your application's architecture, data sources, existing dependencies, and development requirements.
Resolve common installation errors, caching issues, unexpected requests, and configuration problems with these practical solutions.
This error typically occurs when a React Query hook is used outside QueryClientProvider.
Solution: Wrap the relevant component tree with QueryClientProvider and provide a valid QueryClient instance.
Cached queries are considered stale by default, which can trigger requests when components mount, the network reconnects, or window focus returns.
Solution: Configure staleTime and refetch options according to your application's data freshness requirements.
The requested information may still be loading or the query may be disabled.
Solution: Check pending, error, and fetching states before accessing the returned data.
A mutation does not automatically identify every query affected by a server-side change.
Solution: Use queryClient.invalidateQueries() to invalidate affected resources or setQueryData() to update known cache entries.
Inconsistent query keys, multiple query clients, or normal background refetching can create additional requests.
Solution: Use consistent query keys, maintain a stable query client, and inspect requests through DevTools.
The Fetch API does not automatically reject every unsuccessful HTTP response.
Solution: Check response.ok and throw an error for unsuccessful responses.
The DevTools package may be missing or incorrectly configured.
Solution: Install the separate DevTools package, render its component inside QueryClientProvider, and check whether you are using a development build.
Incompatible React and TanStack Query versions can cause package installation problems.
Solution: Review your installed versions using:
npm list react @tanstack/react-querySelect a package version compatible with your project's dependencies.
Take greater control of server state with advanced configuration patterns, framework integrations, and production-ready development practices.
Integrate TanStack Query into Next.js applications using server-side prefetching and hydration. Deliver initial data from the server while allowing client components to maintain interactive query behavior.
When working with server rendering, use request-specific caches where necessary to prevent user data from being shared between requests.
Manage asynchronous data in mobile applications using React Native-compatible query hooks. Integrate network connectivity and application focus handling for appropriate synchronization behavior.
Use typed query functions, response interfaces, and inferred data types to reduce development errors and improve application maintainability.
Configure dependent queries to execute when required information becomes available. Use parallel queries to retrieve separate resources without unnecessary sequential delays.
Create scalable content-loading interfaces using useInfiniteQuery and page-specific query keys. Configure next-page parameters according to your backend API.
Retain selected cached information across browser reloads and application restarts using optional persistence utilities.
Offline mutation recovery requires additional configuration, suitable storage, and appropriate network handling.
Update visible application data before receiving server confirmation. Implement rollback handling to restore previous information if an operation fails.
React Query does not replace authentication, authorization, or backend security mechanisms.
Follow these production best practices.
Thoughtful configuration helps balance responsiveness, network efficiency, data consistency, and security.
Find answers to common questions about installation, compatibility, data caching, troubleshooting, and advanced React Query development.
React Query is an open-source library for fetching, caching, synchronizing, and updating asynchronous server data in React applications.
React Query is the React-specific adapter within the TanStack Query ecosystem. Its modern package is called @tanstack/react-query.
Yes. React Query is distributed under the MIT license and is free for personal and commercial use.
It is used for managing API requests, caching remote information, handling mutations, synchronizing server data, and managing asynchronous request states.
No. Simple applications may not require a dedicated server state library. React Query becomes particularly useful when applications have shared remote data and complex asynchronous workflows.
Install the official @tanstack/react-query package through npm, Yarn, pnpm, or Bun. Its source code is also available on GitHub.
Run npm install @tanstack/react-query inside your React project directory and configure QueryClientProvider.
Yes. The official TanStack Query GitHub repository provides source code, release information, and development resources.
Yes. Install a compatible package version, configure the query provider, and integrate query hooks into your existing components.
TanStack React Query v5 requires React 18 or later and a compatible JavaScript development environment.
Yes. TanStack Query includes TypeScript definitions and supports type inference for asynchronous query results.
Yes. React Query supports Next.js applications, including server-side prefetching, hydration, and client-side data fetching.
Yes. React Query supports React Native applications and can be configured for mobile network connectivity and application focus changes.
Yes. React Query supports asynchronous functions using Axios, Fetch API, GraphQL clients, and other compatible data sources.
Yes. Developers can use page-specific query keys for pagination and useInfiniteQuery for infinite scrolling experiences.
Check your query function, query key, network connection, enabled option, and QueryClientProvider configuration.
Stale queries can refetch when components mount, window focus returns, or the network reconnects. These behaviors are configurable.
Set retry to false in your query configuration or configure it globally through QueryClient defaultOptions.
Use queryClient.clear() to clear connected query and mutation caches. Use removeQueries() when you need to remove selected queries.
staleTime controls data freshness, while gcTime determines how long inactive query data remains cached before removal.
React Query can replace Redux logic dedicated to server data in many applications. Redux may still be useful for complex client-side state management.
Version 5 introduces object-based hook options, updated cache and status terminology, and a minimum React requirement of version 18.
React Query can display available cached information offline and supports optional persistence and paused mutation recovery with appropriate configuration.
Its caching, request coordination, and prefetching capabilities can improve perceived responsiveness. Actual performance depends on application architecture and configuration.
Yes. Its configurable caching, reusable queries, mutation management, and TypeScript support make it suitable for large applications when combined with appropriate architecture and security practices.
Take control of your application's asynchronous data with intelligent caching, flexible query management, and powerful server state synchronization.
Whether you are developing your first React project or maintaining a complex enterprise application, TanStack Query provides practical tools for building more responsive and maintainable digital experiences.
npm install @tanstack/react-querySmarter data fetching. Reliable synchronization. Better React applications.