Open Source • Modern React Development

React Query – Powerful Data Fetching & Server State Management

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
  • Free & Open Source
  • MIT Licensed
  • TypeScript Ready
  • React 18+ Support for v5
  • Developer Friendly
React Query useQuery code example beside a query cache panel showing fresh, stale and fetching queries
  • Intelligent Data Caching
  • Background Synchronization
  • Powerful Query Management
  • Seamless API Integration
Understanding React Query

What Is React Query?

A smarter approach to fetching and managing asynchronous data in modern React applications.

QueryClientProvider setup code and a React app rendering a cached team member list
One QueryClient · one shared cache

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.

How Does React Query Work?

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.

  1. Query key
  2. Query function
  3. Query cache
  4. Components

Why Choose React Query?

  • Reduce repetitive API request code.
  • Manage server data more efficiently.
  • Share cached data between components.
  • Handle loading and error states consistently.
  • Configure automatic data synchronization.
  • Build more maintainable React applications.

React Query works alongside React's existing state management capabilities, allowing developers to separate local interface state from remote application data.

Powerful Capabilities

Everything You Need for Smarter Data Management

Explore the essential features that make React Query a flexible solution for modern, API-driven React applications.

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.

Powerful Mutation Management

Create, update, and delete server resources using the useMutation hook. Manage submission states, handle errors, and refresh affected data after successful operations.

Automatic Error Handling

Access query errors, pending states, and retry controls through a consistent interface. Configure retry behavior according to the needs of individual API requests.

Built-in TypeScript Support

Develop with TypeScript-compatible hooks, configuration options, and type inference. Create more predictable application code with strongly typed query functions and responses.

Automatic Background Refetching

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.

Smart Query Invalidation

Mark selected cached resources as stale whenever underlying server information changes. Targeted invalidation helps maintain consistency across related application components.

Optimistic Updates

Display anticipated changes before the server confirms an operation. Improve perceived responsiveness while using rollback logic to recover from unsuccessful mutations.

React Query DevTools

Inspect query keys, cached information, mutation activity, and data freshness through dedicated developer tools.

Request Deduplication

Coordinate concurrent requests for identical query keys. Components observing the same query can share an in-flight request and access the same cached results.

Pagination and Infinite Scrolling

Create dynamic content feeds, paginated tables, product listings, and load-more experiences with flexible query keys and infinite query functionality.

Query Prefetching

Retrieve anticipated data before users navigate to another page or component. Prefetching can reduce perceived loading times when relevant information is already cached.

Request Cancellation

Cancel unnecessary or outdated asynchronous requests using supported AbortSignal integration. Reduce unnecessary processing when application requirements change.

Built for Modern Development

React Query Compatibility and Supported Technologies

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.

Supported Technologies

  • ReactReact 18+ for v5
  • React NativeSupported
  • Next.jsSupported
  • ViteSupported
  • JavaScriptSupported
  • TypeScriptSupported
  • REST APIsSupported
  • GraphQLSupported
  • AxiosSupported
  • Fetch APISupported
  • TanStack RouterSupported
  • Server-Side RenderingSupported
  • Client-Side RenderingSupported
  • Static Site GenerationSupported with appropriate integration

Real-World Use Cases

  • 01

    E-Commerce Applications

    Manage product catalogs, customer information, shopping cart data, order details, and inventory information retrieved from backend services.

  • 02

    Admin Dashboards

    Fetch analytics, reports, statistics, and management data while maintaining synchronized information across multiple dashboard components.

  • 03

    SaaS Applications

    Manage subscription information, account settings, user permissions, project resources, and other API-driven application features.

  • 04

    Mobile Applications

    Use React Query with React Native to manage remote data, mobile network connectivity, cached responses, and application focus behavior.

  • 05

    Social Media Platforms

    Build dynamic content feeds, user profiles, notifications, comments, and interactive content management experiences.

  • 06

    Financial Applications

    Retrieve account information, transaction records, and financial reports with configurable caching and synchronization policies.

  • 07

    Headless CMS Websites

    Integrate React applications with headless content management systems to retrieve articles, pages, products, and dynamic website content.

  • 08

    Enterprise Applications

    Organize complex server state across large React projects using reusable queries, consistent cache management, and configurable asynchronous workflows.

Official Package Access

Download React Query – Free & Open Source

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.

Choose Your Package Manager

Choose Your Package Manager

Pick the package manager your project already uses and run the command in the project folder.

npm install @tanstack/react-query

Official Package

Install TanStack React Query directly from the npm registry.

Get React Query on npm

GitHub Repository

Explore the source code, releases, documentation resources, and open-source contributions.

React Query GitHub
Download React Query Kit

This 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.

Terminal installing @tanstack/react-query and a package.json listing React Query dependencies

React Query Technical Information

Software Name
React Query
Official Name
TanStack Query
Package Name
@tanstack/react-query
Version Series Covered
v5
Software Category
Server State Management
License
MIT License
Pricing
Free & Open Source
Developer
TanStack and Contributors
Programming Languages
JavaScript, TypeScript
Distribution
npm and GitHub
React Requirement
React 18+ for v5
DevTools
Available Separately
Architecture
Query-Based Data Management
Installation
Package Manager
Quick Start Guide

How to Install and Use React Query

Start managing asynchronous data in your React application with a few simple configuration steps.

  1. Step 01

    Prepare Your React Environment

    Ensure you have Node.js, a compatible package manager, and an existing React application.

    To create a new React application using Vite, run:

    Terminal
    npm create vite@latest my-app -- --template react
    cd my-app
    npm install

    Skip this step if you already have a compatible React project.

  2. Step 02

    Install React Query

    Open your terminal in the project directory and execute:

    Terminal
    npm install @tanstack/react-query

    The package will be added to your project's dependencies.

  3. Step 03

    Configure QueryClientProvider

    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:

    main.jsx
    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>
    );
  4. Step 04

    Fetch Data Using useQuery

    Use the useQuery hook to retrieve asynchronous data and manage loading and error states.

    App.jsx
    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.

  5. Step 05

    Run Your Application

    Start the Vite development server:

    Terminal
    npm run dev

    Open the local development URL displayed in your terminal to test the application.

  6. Step 06

    Install React Query DevTools

    Install the optional developer tools package:

    Terminal
    npm install @tanstack/react-query-devtools

    Import the DevTools component:

    main.jsx
    import {
      ReactQueryDevtools
    } from '@tanstack/react-query-devtools';

    Add it inside QueryClientProvider:

    main.jsx
    <QueryClientProvider client={queryClient}>
      <App />
      <ReactQueryDevtools initialIsOpen={false} />
    </QueryClientProvider>

    You can now inspect cached queries and monitor asynchronous activity during development.

Developer Toolkit

React Query Hooks, Caching and Configuration

Explore the essential hooks and configuration options available for managing asynchronous application data.

Essential React Query Hooks

HookFunctionality
useQueryFetch and cache asynchronous data
useMutationManage server-side data changes
useInfiniteQueryHandle infinite scrolling and incremental loading
useQueriesManage multiple queries
useQueryClientAccess the shared query client
useIsFetchingMonitor active query requests
useIsMutatingMonitor active mutations
useSuspenseQueryIntegrate queries with React Suspense
useSuspenseQueriesManage multiple Suspense queries
useMutationStateAccess matching mutation states

Important Configuration Options

OptionPurpose
staleTimeControls how long data remains fresh
gcTimeControls inactive cache retention
retryConfigures failed query retries
enabledControls automatic query execution
refetchOnWindowFocusControls refetching when window focus returns
refetchOnReconnectControls refetching after network reconnection
refetchIntervalConfigures periodic data fetching
placeholderDataDisplays temporary data while a query resolves
initialDataSupplies initial query cache data
selectTransforms or selects returned data

Understanding Query Keys

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.

Basic query keyqueryKey: ['products']
Product detailsqueryKey: ['products', productId]
Filtered productsqueryKey: ['products', { category, page }]

staleTime vs gcTime

staleTime

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

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.

Global Query Configuration

Adjust these settings according to your application's data freshness requirements, network conditions, and expected user interactions.

queryClient.js
const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 60000,
      gcTime: 300000,
      retry: 2,
      refetchOnWindowFocus: false
    }
  }
});
Compare Your Options

React Query Versions and Popular Alternatives

Understand the differences between major React Query versions and discover how TanStack Query compares with other popular development libraries.

React Query v3 vs v4 vs v5

Featurev3v4v5
Packagereact-query@tanstack/react-query@tanstack/react-query
BrandingReact QueryTanStack QueryTanStack Query
Hook SyntaxMultiple SignaturesMultiple SignaturesObject-Based
Cache RetentioncacheTimecacheTimegcTime
Pending StatusisLoadingisLoadingisPending
Previous Page DatakeepPreviousData OptionkeepPreviousData OptionplaceholderData
UsageLegacy ProjectsExisting ProjectsModern Projects

React Query vs Redux

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.

React Query vs SWR

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.

React Query vs Axios

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.

React Query vs RTK Query

RTK Query integrates directly with Redux Toolkit. React Query provides separate server state management without requiring a Redux store.

Alternatives Comparison

LibraryPrimary PurposeSuitable For
React QueryServer State ManagementAPI-Driven React Apps
Redux ToolkitGeneral State ManagementComplex Application State
SWRData FetchingConcise Fetching Workflows
RTK QueryAPI Data ManagementRedux-Based Applications
AxiosHTTP RequestsNetwork Communication
Apollo ClientGraphQL Data ManagementGraphQL Applications
ZustandClient State ManagementLightweight Global State

The most suitable library depends on your application's architecture, data sources, existing dependencies, and development requirements.

Common Issues & Solutions

React Query Troubleshooting Guide

Resolve common installation errors, caching issues, unexpected requests, and configuration problems with these practical solutions.

No QueryClient Set Error

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.

React Query Keeps Refetching

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.

useQuery Returns Undefined

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.

Data Does Not Update After a Mutation

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.

Duplicate API Requests

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.

React Query Does Not Detect API Errors

The Fetch API does not automatically reject every unsuccessful HTTP response.

Solution: Check response.ok and throw an error for unsuccessful responses.

React Query DevTools Not Showing

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.

Installation and Dependency Errors

Incompatible React and TanStack Query versions can cause package installation problems.

Solution: Review your installed versions using:

npm list react @tanstack/react-query

Select a package version compatible with your project's dependencies.

Build Beyond the Basics

Advanced React Query Features and Best Practices

Take greater control of server state with advanced configuration patterns, framework integrations, and production-ready development practices.

React Query With Next.js

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.

React Query With React Native

Manage asynchronous data in mobile applications using React Native-compatible query hooks. Integrate network connectivity and application focus handling for appropriate synchronization behavior.

TypeScript Integration

Use typed query functions, response interfaces, and inferred data types to reduce development errors and improve application maintainability.

Dependent and Parallel Queries

Configure dependent queries to execute when required information becomes available. Use parallel queries to retrieve separate resources without unnecessary sequential delays.

Infinite Scrolling and Pagination

Create scalable content-loading interfaces using useInfiniteQuery and page-specific query keys. Configure next-page parameters according to your backend API.

Offline Data Persistence

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.

Optimistic User Interfaces

Update visible application data before receiving server confirmation. Implement rollback handling to restore previous information if an operation fails.

Server State Security

React Query does not replace authentication, authorization, or backend security mechanisms.

Follow these production best practices.

  • Use secure HTTPS API connections.
  • Validate user permissions on the backend.
  • Avoid placing sensitive credentials in query keys.
  • Clear user-specific cached information during logout.
  • Configure appropriate retry policies.
  • Avoid unnecessarily persisting sensitive information.
  • Keep dependencies updated.
  • Use consistent query key structures.
  • Configure freshness according to each resource.
  • Monitor query behavior during development.

Thoughtful configuration helps balance responsiveness, network efficiency, data consistency, and security.

Need Help?

Frequently Asked Questions About React Query

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.

Start Building Today

Build Smarter React Applications With React Query

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-query
  • 100% Free & Open Source
  • MIT License
  • TypeScript Compatible
  • React 18+ Support for v5
  • No Subscription Required

Smarter data fetching. Reliable synchronization. Better React applications.