Skip to content
State Management

TanStack Query: State Management Guide

Powerful asynchronous state management for React. Automatic caching, background updates, stale-while-revalidate, and DevTools included.

★ Editor's Pick TypeScript MIT
66.8M weekly downloads
50.3k GitHub stars
13.3 kB min+gzip bundle size
v5.102.5 latest version

Figures above measured on from the npm registry (latest version, last-week downloads) and the GitHub API (stars). Not copied from the project's own README, and re-measured rather than edited by hand, so the date tells you exactly how old these numbers are.

How the bundle size was measured. We installed @tanstack/react-query@5.102.5 on its own, bundled export * from '@tanstack/react-query' with esbuild (esm, browser, minified, production), marked React external because your app already has it, and gzipped the result. Measured . This is the ceiling, not the typical cost: it imports the entire public surface with no tree-shaking credit. Pull one component from a well-shaken library and you'll pay a fraction of it. We publish the ceiling because it's the number we can reproduce, and reproducing it is the point. For TanStack Query, a typical import -- just { useQuery } from @tanstack/react-query, bundled and gzipped the same way -- measures 4.1 kB min+gzip, against the 13.3 kB min+gzip ceiling above.

data-fetchingcachingasyncserver-statedevtools

A real, running TanStack Query demo, not a screenshot -- every variant documented below is interactive.

Maintenance Health

Who keeps TanStack Query alive, and how it behaves when something breaks -- measured from the npm registry and the package's own repository, not the project's README.

Who maintains this
3 npm publishers • Volunteer team
Last npm release
Last repo activity
Open issues
174
Runtime dependencies
1
Tree-shakeable
Yes -- no side effects declared
React peer range
^18 || ^19

TL;DR: TanStack Query manages server state in React. useQuery() fetches and caches data; useMutation() handles writes with optimistic updates. Automatic background refetches, stale-while-revalidate caching, and DevTools included. ~13kB. Official docs: tanstack.com/query.

What is TanStack Query?

TanStack Query (formerly React Query) manages server state - data that lives on a server and needs to be fetched, cached, synchronized, and updated. It handles the lifecycle that every data-fetching implementation reinvents: loading states, error states, background refetches, cache invalidation, and optimistic updates.

The key insight: your component shouldn't manage fetching logic. useQuery subscribes to a cache entry; TanStack Query handles the rest.

I ripped out roughly 40 custom useEffect data-fetching hooks from a dashboard app when I adopted this library, and the bug reports about stale data after navigation basically stopped overnight. Turns out most of those bugs weren't logic errors, they were cache-invalidation problems nobody had actually solved, just papered over with key props that forced remounts.

When to use it

Use TanStack Query when your app fetches data from an API. It replaces:

  • useEffect + useState + manual loading/error flags
  • Redux/Zustand stores used purely as an API response cache
  • Custom data-fetching hooks that don't handle staleness

Skip it for client-only state (UI toggles, form state, wizard steps) - use Zustand or Jotai instead.

Key Features

  • Automatic caching - responses cached by query key; deduplicates parallel requests
  • Stale-while-revalidate - shows cached data immediately, refetches in background
  • Window focus refetching - refetches when the user returns to the tab
  • Mutations - useMutation for POST/PUT/DELETE with optimistic updates
  • Infinite queries - useInfiniteQuery for pagination and infinite scroll
  • DevTools - visual inspector for cache state, query status, and timing

Defaults, measured

The docs list the defaults. We wanted to watch them happen. So we ran @tanstack/query-core, the engine under the React hooks, against a counting fake queryFn on Node 22.23.3. No network, no React, just call counts and a clock. Two releases gave identical numbers: 5.102.5, the version this page tracks, and 5.108.0, the newest on npm on 2026-11-18.

ScenarioMeasuredWhat it tells you
Three components mount on one queryKey1 fetchDedup is real. The key is the whole contract.
Second mount, default staleTime (0)2 fetches in totalCached data shows at once, then refetches on every mount.
Second mount, staleTime: 30_0001 fetchOne option removes the extra request.
Tab refocus, default staleTimerefetch (1 -> 2 fetches)Switching tabs costs a request.
Tab refocus, staleTime: 30_000no refetchSame option, same effect.
Always-failing queryFn, browser4 attempts at 0, 1, 3 and 7 sDefault retry: 3 with 1, 2 and 4 s backoff.
Same failing queryFn, server1 attemptretry defaults to 0 there.
Unused cache entry, browsergcTime 300,000 msFive minutes, then it's collected.
Unused cache entry, servergcTime InfinityNothing is collected while the client lives.

Does a default staleTime of 0 surprise you? It surprised us a little. Zero means every result counts as stale the moment it arrives, so "cached" really means "shown first, verified second". That's a sound default for correctness. It's a noisy one for a dashboard that remounts a lot.

The server and browser defaults differ

The library decides once whether it's running on a server. No window, or a Deno global, means server. That flips retry from 3 to 0 and gcTime from five minutes to infinity; the source reads retry ?? (isServer() ? 0 : 3). Two practical consequences follow.

A client created at module level in a long-running Node process never forgets a cached entry, which is why the standard SSR advice is one client per request. And a test environment that defines window, jsdom for one, should get the browser numbers, so a test of a failing query waits about 7 seconds for its error state until you set retry: false on the test client. We didn't run jsdom, only a bare window stub, so check that one on your setup. When the guess is wrong (a service worker has no window but behaves like a client), environmentManager.setIsServer(() => false) overrides it.

Structural sharing keeps references stable

A refetch that returns data deep-equal to the cached copy keeps the old object: first === second was true. When one leaf changed, the root and the changed branch got new references while the untouched siblings kept theirs. Those are the references React compares, so a background refetch that found nothing new doesn't hand your components new props.

Reproduce the first row

import { QueryClient, QueryObserver } from '@tanstack/query-core'

const client = new QueryClient()
let calls = 0
const queryFn = async () => {
  calls += 1
  return { ok: true }
}

const watchers = [1, 2, 3].map(
  () => new QueryObserver(client, { queryKey: ['demo'], queryFn }),
)
watchers.forEach((w) => w.subscribe(() => {}))
await new Promise((r) => setTimeout(r, 100))
console.log(calls) // 1

For the focus rows, call client.mount() first, then focusManager.setFocused(false) and setFocused(true). QueryClientProvider does the mounting for you in React; a bare client doesn't.

Installation

npm install @tanstack/react-query
# DevTools (dev only):
npm install @tanstack/react-query-devtools

Basic Usage

// 1. Wrap your app
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'

const queryClient = new QueryClient()

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <MyApp />
    </QueryClientProvider>
  )
}

// 2. Fetch data in any component
import { useQuery } from '@tanstack/react-query'

function UserProfile({ userId }: { userId: string }) {
  const { data, isPending, isError } = useQuery({
    queryKey: ['users', userId],
    queryFn: () => fetch(`/api/users/${userId}`).then(r => r.json()),
  })

  if (isPending) return <Skeleton />
  if (isError) return <ErrorMessage />
  return <Profile user={data} />
}

Mutations with Cache Invalidation

import { useMutation, useQueryClient } from '@tanstack/react-query'

function DeleteButton({ postId }: { postId: string }) {
  const queryClient = useQueryClient()

  const deleteMutation = useMutation({
    mutationFn: (id: string) => fetch(`/api/posts/${id}`, { method: 'DELETE' }),
    onSuccess: () => {
      // Re-fetch the posts list after deletion
      queryClient.invalidateQueries({ queryKey: ['posts'] })
    },
  })

  return (
    <button
      onClick={() => deleteMutation.mutate(postId)}
      disabled={deleteMutation.isPending}
    >
      Delete
    </button>
  )
}

Infinite Queries for Pagination

useInfiniteQuery is the one I reach for most on feed-style UIs, comment threads, anything with a "load more" button or scroll-triggered pagination. It tracks page cursors for you instead of you juggling an array of page numbers in component state:

import { useInfiniteQuery } from '@tanstack/react-query'

function CommentFeed({ postId }: { postId: string }) {
  const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = useInfiniteQuery({
    queryKey: ['comments', postId],
    queryFn: ({ pageParam }) =>
      fetch(`/api/posts/${postId}/comments?cursor=${pageParam}`).then(r => r.json()),
    initialPageParam: 0,
    getNextPageParam: (lastPage) => lastPage.nextCursor ?? undefined,
  })

  return (
    <div>
      {data?.pages.map((page) => page.comments.map((c: Comment) => (
        <CommentRow key={c.id} comment={c} />
      )))}
      {hasNextPage && (
        <button onClick={() => fetchNextPage()} disabled={isFetchingNextPage}>
          {isFetchingNextPage ? 'Loading...' : 'Load more'}
        </button>
      )}
    </div>
  )
}

The cache stores each page separately, so invalidateQueries(['comments', postId]) after a new comment is posted refetches only the affected pages, not the whole feed the user already scrolled past.

TypeScript Tips

Type your query functions for full inference:

interface Post { id: string; title: string; body: string }

const { data } = useQuery({
  queryKey: ['posts'],
  queryFn: (): Promise<Post[]> => fetch('/api/posts').then(r => r.json()),
})
// data is Post[] | undefined  -  automatically inferred

Common Gotchas

  • queryKey must be serializable - use primitive values or plain objects; avoid class instances or functions in the key
  • staleTime defaults to 0 - every mount triggers a background refetch. Set staleTime: 5 * 60 * 1000 globally for data that doesn't change often
  • Parallel queries - use useQueries for a dynamic list of queries rather than calling useQuery in a loop
  • Error boundaries - set throwOnError: true on the QueryClient to let errors bubble to React Error Boundaries
  • Zustand - use Zustand for client UI state alongside TanStack Query for server state
  • Recharts - pass useQuery data directly to Recharts chart components for live-updating dashboards with automatic background refetches
  • React 19 use() hook guide - React 19's use() hook and Actions complement TanStack Query for server-first patterns
  • TypeScript Generics Guide - useQuery<TData, TError> and useMutation are fully generic; understand the patterns here

Frequently Asked Questions

What is the difference between TanStack Query and SWR?

Both handle server state caching but TanStack Query has a significantly richer feature set: built-in DevTools, mutation management with optimistic updates, infinite queries, query invalidation, and prefetching. SWR is simpler and smaller. For complex data requirements, TanStack Query is the better choice.

Does TanStack Query replace Zustand or Redux?

Only for server state. TanStack Query manages data that comes from an API - fetching, caching, and synchronising it. For client-only state (UI toggles, form state, user preferences), you still need Zustand, Jotai, or useState.

How do I prevent TanStack Query from refetching too often?

Set staleTime on the QueryClient to control how long data is considered fresh. The default is 0, which refetches on every mount. Setting staleTime: 5 * 60 * 1000 means data is reused for 5 minutes before a background refetch occurs.

How do I invalidate the cache after a mutation?

In the useMutation onSuccess callback, call queryClient.invalidateQueries with the relevant query key. This marks the cached data as stale and triggers a background refetch in any mounted component that subscribes to that query.

Can TanStack Query work with server-side rendering?

Yes. Use the HydrationBoundary and dehydrate utilities to prefetch queries on the server and rehydrate state on the client. Next.js App Router and React Server Components are fully supported.

What are TanStack Query's default retry and cache times?

Measured with query-core 5.102.5 and 5.108.0: in a browser a failing query makes 4 attempts at 0, 1, 3 and 7 seconds (retry 3 with 1, 2 and 4 second backoff), an unused cache entry is collected after 300,000 ms, and staleTime is 0, so every mount and every tab refocus refetches. On a server, with no window, retry is 0 and gcTime is Infinity. Setting staleTime to 30 seconds removed the extra mount and focus fetches in the same test.