Overview

@tanstack/react-query, part of the TanStack suite, is a data-fetching library specifically designed for React applications. It addresses the challenges of managing server state, which differs fundamentally from client-side state. Server state is asynchronous, often requires caching, invalidation, and background synchronization, and can be updated by multiple users or processes. React Query provides a set of hooks and utilities that abstract away much of this complexity, allowing developers to focus on application logic rather than the intricacies of data synchronization and caching.

The library is particularly well-suited for applications that rely heavily on external APIs for data. It automatically handles common patterns such as caching fetched data, refetching stale data in the background, retrying failed requests, and managing pagination and infinite scrolling. This reduces the amount of boilerplate code typically required for these operations. For instance, when a user navigates away from a page and then returns, React Query can serve cached data instantly while simultaneously refetching in the background to ensure data freshness. This approach improves perceived performance and user experience.

Developers using @tanstack/react-query can implement optimistic UI updates, where the user interface is updated immediately after an action, even before the server confirms the change. If the server request fails, React Query can automatically revert the UI to its previous state. This pattern contributes to a highly responsive application feel. The library's opinionated but flexible design aims to provide a robust solution for server state management without imposing strict architectural patterns on the rest of the application. It integrates seamlessly with existing React component structures and other state management solutions for client-side state, such as Zustand or Jotai.

While primarily known for its React integration, the underlying TanStack Query core is framework-agnostic, with specific adapters available for other popular JavaScript frameworks like Vue, Solid, Svelte, and Qwik. This broad compatibility allows developers familiar with the core concepts to apply them across different ecosystems.

Key features

  • Automatic Caching and Data Synchronization: Manages a cache of server data, automatically refetching and updating components when data becomes stale or invalidates.
  • Background Refetching: Queries can refetch data in the background to keep the UI updated without blocking user interaction, improving perceived performance.
  • Optimistic UI Updates: Supports updating the UI immediately after a mutation, assuming the server operation will succeed, and provides mechanisms to revert on failure.
  • Query Invalidation and Refetching: Offers fine-grained control over when and how data is invalidated and refetched, allowing for precise cache management.
  • Automatic Retries and Error Handling: Configurable retry logic for failed queries and mutations, reducing the need for manual error handling.
  • Pagination and Infinite Loading: Provides dedicated hooks and utilities to simplify the implementation of paginated and infinitely scrolling lists.
  • Devtools: Includes a dedicated browser extension for inspecting query states, caches, and mutations, aiding in debugging and development.
  • Type Safety: Built with TypeScript, offering strong type inference for queries, mutations, and cache data.

Pricing

@tanstack/react-query is a free and open-source library. There are no licensing fees for its usage in commercial or non-commercial projects.

Feature Cost (as of 2026-06-07) Notes
Core Library Usage Free Fully open-source under the MIT License.
Community Support Free Available via GitHub issues and Discord.
Commercial Support Not offered directly by TanStack Third-party consulting may be available.

Common integrations

  • React: Primary integration via @tanstack/react-query package, offering hooks like useQuery and useMutation for React components. Refer to the React Query API reference for specific usage.
  • Vue: Integrated through @tanstack/vue-query, providing a similar API with Vue composition functions.
  • Solid: Supported by @tanstack/solid-query, adapting the query patterns for SolidJS.
  • Svelte: Integration via @tanstack/svelte-query, offering Svelte-specific stores and functions.
  • Qwik: Utilizes @tanstack/qwik-query for integration with the Qwik framework.
  • Axios: Commonly used as the HTTP client for data fetching within React Query applications. See the Axios HTTP client documentation for setup.
  • Fetch API: Can be used directly as the data fetching mechanism, leveraging native browser capabilities.

Alternatives

  • SWR: A React Hooks library for data fetching, known for its lightweight footprint and focus on the "stale-while-revalidate" caching strategy.
  • Apollo Client: A comprehensive state management library for GraphQL, offering sophisticated caching, normalized store, and optimistic UI for GraphQL APIs.
  • RTK Query: A data fetching and caching solution built on top of Redux Toolkit, providing a powerful way to manage server state with Redux.

Getting started

To get started with @tanstack/react-query in a React application, you typically install the package and wrap your application with a QueryClientProvider. This provider makes the query client available to all components within its tree, allowing them to use the useQuery and useMutation hooks.

First, install the package:

npm install @tanstack/react-query @tanstack/react-query-devtools

Then, set up your QueryClient and QueryClientProvider in your application's root (e.g., App.js or index.js):

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

const queryClient = new QueryClient();

ReactDOM.createRoot(document.getElementById('root')).render(
  
    
      
      
    
  
);

Now, you can use useQuery in your components to fetch data:

import React from 'react';
import { useQuery } from '@tanstack/react-query';

async function fetchTodos() {
  const response = await fetch('https://jsonplaceholder.typicode.com/todos');
  if (!response.ok) {
    throw new Error('Network response was not ok');
  }
  return response.json();
}

function Todos() {
  const { data, isLoading, error } = useQuery({
    queryKey: ['todos'],
    queryFn: fetchTodos,
  });

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

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

export default Todos;

This example demonstrates fetching a list of todos from a public API. The useQuery hook handles the loading, error, and data states, making it simpler to render UI based on the server state. The queryKey uniquely identifies the query in the cache, and queryFn is the asynchronous function that fetches the data.