Overview

@tanstack/react-query is a specialized library designed to streamline server state management within React applications. It provides a set of hooks and utilities that abstract away common complexities associated with fetching, caching, synchronizing, and updating asynchronous data. The library is part of the broader TanStack ecosystem, which includes other tools like TanStack Table and TanStack Router, all built with a focus on type safety and performance.

The primary use case for @tanstack/react-query involves scenarios where an application frequently interacts with external APIs or databases. Rather than manually managing fetch states, loading indicators, error handling, and data revalidation, developers can utilize @tanstack/react-query to handle these concerns declaratively. It automatically caches fetched data, invalidates stale data, and can refetch data in the background, ensuring the UI remains updated with the latest information without explicit manual intervention.

Developers working on single-page applications (SPAs) or complex dashboards that display frequently changing data often find value in @tanstack/react-query. It simplifies tasks such as prefetching data for smoother navigation, implementing infinite scrolling, and managing dependent queries. For instance, when a user navigates to a new page, @tanstack/react-query can be configured to fetch necessary data preemptively, reducing perceived loading times. Its architecture is built around the concept of queries and mutations, providing clear patterns for both reading and writing server data.

One of the key benefits highlighted by its maintainers is its ability to facilitate optimistic UI updates. This feature allows an application's UI to update immediately after a user action, assuming the server operation will succeed, thereby enhancing the user experience by providing instant feedback. If the server operation fails, @tanstack/react-query can automatically roll back the UI state, maintaining data consistency. This approach contrasts with traditional methods where the UI waits for a server response before updating, which can lead to noticeable delays.

While @tanstack/react-query is often associated with React, the core TanStack Query library is framework-agnostic, with specific adapters for various UI libraries. This modular design allows the underlying logic for data fetching and caching to be shared across different frontend technologies, providing a consistent API for server state management regardless of the chosen framework. This design principle can be particularly useful in projects that involve multiple frontend frameworks or anticipate future migrations.

Key features

  • Automatic Caching and Data Synchronization: Manages a cache of server data, automatically revalidating and refetching data in the background to keep the UI synchronized with the backend.
  • Declarative Data Fetching: Provides hooks like useQuery and useMutation for declarative data fetching and updates, reducing the amount of imperative code required to manage asynchronous operations.
  • Optimistic UI Updates: Supports updating the UI instantly based on the assumption of a successful server action, then reconciles with the actual server response, improving user experience.
  • Stale-While-Revalidate Strategy: Implements a "stale-while-revalidate" caching strategy, immediately serving cached data while refetching in the background to ensure data freshness. This strategy is comparable to that used by other data fetching libraries such as SWR, which implements a similar approach for React applications (SWR revalidation documentation).
  • Automatic Retries and Error Handling: Configurable automatic retries for failed queries and mutations, along with robust error handling mechanisms.
  • Background Refetching: Automatically refetches data when the window regains focus, upon network reconnection, or at specified intervals, ensuring data remains fresh.
  • Parallel and Dependent Queries: Supports running multiple queries in parallel and managing queries that depend on the results of other queries.
  • Pagination and Infinite Scrolling: Provides utilities for implementing efficient pagination and infinite scrolling patterns for lists of data.
  • Type Safety (with TypeScript): Built with TypeScript, offering strong type inference and safety for better developer experience and fewer runtime errors.

Pricing

As of 2026-06-18, @tanstack/react-query is part of the TanStack Query project, which is free and open-source.

Feature Availability
Core Library Free and Open-Source
Community Support Free
Commercial Licensing Not applicable (MIT License)

For detailed licensing information, refer to the project's official GitHub repository, which typically uses an MIT License.

Common integrations

  • React: Primary integration point, offering specific hooks like useQuery and useMutation (TanStack React Query API Reference).
  • Axios: Commonly used HTTP client for making API requests within queries (Axios HTTP Client documentation).
  • Fetch API: Native browser API for network requests, often used directly or wrapped within query functions.
  • TypeScript: Fully integrated for type-safe development, especially when defining query keys and data types (TypeScript official documentation).
  • Other TanStack Libraries: Seamlessly integrates with TanStack Table, TanStack Router, and TanStack Virtual for a unified development experience across different concerns.

Alternatives

  • SWR: A React Hooks library for data fetching, also employing a "stale-while-revalidate" strategy.
  • Apollo Client: A comprehensive state management library for GraphQL, offering sophisticated caching and normalized data stores.
  • RTK Query: A data fetching and caching solution built on top of Redux Toolkit, providing similar features to @tanstack/react-query within the Redux ecosystem.

Getting started

To begin using @tanstack/react-query in a React application, first install the necessary packages:

npm install @tanstack/react-query @tanstack/react-query-devtools
# or
yarn add @tanstack/react-query @tanstack/react-query-devtools

Then, wrap your application with a QueryClientProvider and define your first query. This example fetches a list of todos from a public API:

import React from 'react';
import ReactDOM from 'react-dom/client';
import { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query';
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';

const queryClient = new QueryClient();

function App() {
  const { isLoading, error, data } = useQuery({
    queryKey: ['todos'],
    queryFn: () =>
      fetch('https://jsonplaceholder.typicode.com/todos').then((res) =>
        res.json(),
      ),
  });

  if (isLoading) return <p>Loading...</p>;
  if (error) return <p>An error has occurred: {error.message}</p>;

  return (
    <div>
      <h1>Todos</h1>
      <ul>
        {data.map((todo) => (
          <li key={todo.id}>{todo.title}</li>
        ))}
      </ul>
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <QueryClientProvider client={queryClient}>
      <App />
      <ReactQueryDevtools initialIsOpen={false} />
    </QueryClientProvider>
  </React.StrictMode>,
);

This setup fetches todos, caches them, and automatically handles loading and error states. The ReactQueryDevtools can be used to monitor cache activity and inspect queries during development (TanStack Query Devtools documentation).