TanStack Query: Data Fetching for React
You start with a useEffect that calls fetch and stores the result in state. Then you add an isLoading flag, then an error state, then a check so a slow response doesn't overwrite a newer one. A second component needs the same data, so it fires the same request again, and after a save somewhere else both of them show stale numbers until someone hits refresh.
TanStack Query (formerly React Query) exists to take that code off your hands. It treats data from your API as its own kind of state, with caching, background refetching and request deduplication built in. This post walks through v5: setup, useQuery, mutations and optimistic updates, pagination and infinite scroll, error handling, query key conventions, and how it compares to SWR and RTK Query.
It's one of the most widely used data fetching libraries in the React ecosystem, so most problems you hit already have an answer in the docs or a GitHub discussion. Version 5 (released in late 2023) simplified the API to a single object argument, improved TypeScript inference, and renamed a few options like cacheTime to gcTime.
What is TanStack Query?
The core idea is that server state behaves differently from client state, and most state libraries treat them the same. TanStack Query started with React and now has adapters for Vue, Solid, Angular and Svelte.
Client state (UI toggles, form values, the selected tab) lives in your app and you control it completely. Server state lives somewhere else. You don't own it, other users can change it while you're looking at it, and every read is asynchronous. Here's what the library handles for you:
- Automatic caching: Responses are cached by query key and reused across components
- Background refetching: Stale data is refetched when users revisit a page or refocus the window
- Deduplication: Duplicate requests for the same data are collapsed into one network call
- Pagination & infinite scroll: First-class primitives for paginated and cursor-based APIs
- Mutations with rollback: Optimistic updates with automatic rollback on failure
- DevTools: A visual inspector showing every query's status and cached data
TanStack Query sits between your components and the network, managing cache, background refetching, and state
Installation & Setup
v5 needs React 18 or later and has no other required dependencies. Setup is three steps.
Install the package
Install @tanstack/react-query and optionally the DevTools package for debugging.
# npm
npm install @tanstack/react-query
# With DevTools (recommended for development)
npm install @tanstack/react-query @tanstack/react-query-devtools
# yarn / pnpm
yarn add @tanstack/react-query @tanstack/react-query-devtools
pnpm add @tanstack/react-query @tanstack/react-query-devtools
Wrap your app with QueryClientProvider
Create a QueryClient instance and provide it at the root of your application.
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
import ReactDOM from 'react-dom/client'
import App from './App'
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 1000 * 60 * 5, // 5 minutes: data stays fresh before refetch
retry: 2, // retry failed requests twice
refetchOnWindowFocus: true, // refetch when user returns to tab
},
},
})
ReactDOM.createRoot(document.getElementById('root')!).render(
<QueryClientProvider client={queryClient}>
<App />
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
)
Start fetching data with useQuery
That's it. Any component under the provider can now call useQuery. If you forget the provider, you'll get "No QueryClient set, use QueryClientProvider to set one" the first time a hook runs.
staleTime controls how long cached data is considered fresh (no network request made). gcTime (formerly cacheTime) controls how long unused cached data is kept in memory before garbage collection. They do different jobs, and staleTime is the one to tune first.
Querying Data with useQuery
You give useQuery two things: a query key, which identifies the data in the cache, and a query function, which is any async function that returns a promise. It tracks loading, error and success states so you don't have to.
import { useQuery } from '@tanstack/react-query'
interface Todo {
id: number
title: string
completed: boolean
userId: number
}
async function fetchTodos(): Promise<Todo[]> {
const res = await fetch('https://jsonplaceholder.typicode.com/todos')
if (!res.ok) throw new Error('Failed to fetch todos')
return res.json()
}
function TodoList() {
const {
data: todos,
isLoading,
isError,
error,
isFetching, // true when background refetch is happening
refetch,
} = useQuery({
queryKey: ['todos'], // unique cache key, array format preferred
queryFn: fetchTodos,
staleTime: 1000 * 60 * 2, // override default: 2 minutes fresh
})
if (isLoading) return <p>Loading todos...</p>
if (isError) return <p>Error: {error.message}</p>
return (
<div>
<header>
<h2>Todos {isFetching && '(updating...)'}</h2>
<button onClick={() => refetch()}>Refresh</button>
</header>
<ul>
{todos?.map(todo => (
<li key={todo.id} style={{ opacity: todo.completed ? 0.5 : 1 }}>
{todo.title}
</li>
))}
</ul>
</div>
)
}
Dynamic Query Keys
Put variables in the query key and the query reruns whenever they change. That's how you fetch a resource by ID or apply a filter.
// Fetch a single user; reruns when userId changes
function useUser(userId: number) {
return useQuery({
queryKey: ['users', userId], // key includes the variable
queryFn: () => fetchUser(userId),
enabled: !!userId, // skip if userId is falsy
})
}
// Filtered list; reruns when filter changes
function useTodos(filter: 'all' | 'done' | 'pending') {
return useQuery({
queryKey: ['todos', { filter }],
queryFn: () => fetchTodos(filter),
})
}
// Dependent query: waits for a previous query to finish
function useUserPosts(userId?: number) {
return useQuery({
queryKey: ['posts', { userId }],
queryFn: () => fetchPostsByUser(userId!),
enabled: !!userId, // won't run until userId is available
})
}
// Usage: chain two queries
function UserWithPosts({ userId }: { userId: number }) {
const { data: user } = useUser(userId)
const { data: posts } = useUserPosts(user?.id) // enabled only after user loads
// ...
}
Wrap useQuery calls in custom hooks (like useUser above). This co-locates your query key and fetcher, makes the hook reusable across components, and keeps fetching details out of your JSX. I do this for every query in a real app, even ones used in a single place.
Mutations with useMutation
useQuery reads; useMutation writes (POST, PUT, PATCH, DELETE). After a successful mutation, you typically invalidate related queries so they refetch with fresh data.
import { useMutation, useQueryClient } from '@tanstack/react-query'
async function createTodo(newTodo: { title: string }): Promise<Todo> {
const res = await fetch('/api/todos', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(newTodo),
})
if (!res.ok) throw new Error('Failed to create todo')
return res.json()
}
function AddTodoForm() {
const queryClient = useQueryClient()
const [title, setTitle] = useState('')
const mutation = useMutation({
mutationFn: createTodo,
// Called immediately on success, before the response propagates
onSuccess: (newTodo) => {
// Invalidate and refetch the todos list
queryClient.invalidateQueries({ queryKey: ['todos'] })
// OR: manually update the cache without a network request
queryClient.setQueryData<Todo[]>(['todos'], (old = []) => [
...old,
newTodo,
])
},
onError: (error) => {
console.error('Create failed:', error)
},
})
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault()
if (!title.trim()) return
mutation.mutate({ title })
setTitle('')
}
return (
<form onSubmit={handleSubmit}>
<input
value={title}
onChange={e => setTitle(e.target.value)}
placeholder="New todo..."
disabled={mutation.isPending}
/>
<button type="submit" disabled={mutation.isPending}>
{mutation.isPending ? 'Adding...' : 'Add Todo'}
</button>
{mutation.isError && (
<p style={{ color: 'red' }}>Error: {mutation.error.message}</p>
)}
</form>
)
}
Optimistic Updates
With an optimistic update, the UI shows the result of a mutation before the server confirms it. The rollback isn't magic, though: you snapshot the cache in onMutate, return it as context, and restore it yourself in onError. The pattern below does exactly that.
const toggleTodo = useMutation({
mutationFn: ({ id, completed }: { id: number; completed: boolean }) =>
fetch(`/api/todos/${id}`, {
method: 'PATCH',
body: JSON.stringify({ completed }),
}).then(r => r.json()),
onMutate: async ({ id, completed }) => {
// Cancel any outgoing refetches so they don't overwrite optimistic update
await queryClient.cancelQueries({ queryKey: ['todos'] })
// Snapshot current value for rollback
const previousTodos = queryClient.getQueryData<Todo[]>(['todos'])
// Optimistically update cache
queryClient.setQueryData<Todo[]>(['todos'], old =>
old?.map(todo => (todo.id === id ? { ...todo, completed } : todo)) ?? []
)
// Return snapshot for onError rollback
return { previousTodos }
},
onError: (_err, _vars, context) => {
// Roll back to snapshot if mutation fails
if (context?.previousTodos) {
queryClient.setQueryData(['todos'], context.previousTodos)
}
},
onSettled: () => {
// Always refetch to ensure cache is in sync with server
queryClient.invalidateQueries({ queryKey: ['todos'] })
},
})
Advanced Features
In v4 this was the keepPreviousData: true option. In v5 you pass placeholderData: keepPreviousData instead. Either way, the old page stays on screen while the next one loads, so the list doesn't flash empty.
import { keepPreviousData } from '@tanstack/react-query'
function PaginatedList() {
const [page, setPage] = useState(1)
const { data, isFetching } = useQuery({
queryKey: ['users', page],
queryFn: () => fetchUsers({ page, limit: 10 }),
placeholderData: keepPreviousData, // show old data while fetching new page
})
return (
<div>
<ul>
{data?.users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
<nav>
<button onClick={() => setPage(p => p - 1)} disabled={page === 1}>
Previous
</button>
<span>Page {page}</span>
<button
onClick={() => setPage(p => p + 1)}
disabled={!data?.hasMore}
>
{isFetching ? 'Loading...' : 'Next'}
</button>
</nav>
</div>
)
}
useInfiniteQuery handles "load more" buttons and infinite scroll. Every page is stored under one cache entry, and you get them back as data.pages, an array you map over (or flatten yourself).
import { useInfiniteQuery } from '@tanstack/react-query'
import { useInView } from 'react-intersection-observer'
function InfiniteList() {
const { ref, inView } = useInView()
const {
data,
fetchNextPage,
hasNextPage,
isFetchingNextPage,
} = useInfiniteQuery({
queryKey: ['infinite-users'],
queryFn: ({ pageParam }) => fetchUsers({ cursor: pageParam }),
initialPageParam: undefined,
getNextPageParam: (lastPage) => lastPage.nextCursor ?? undefined,
})
// Auto-fetch next page when sentinel div enters viewport
useEffect(() => {
if (inView && hasNextPage) fetchNextPage()
}, [inView, hasNextPage])
return (
<div>
{data?.pages.map((page, i) => (
<Fragment key={i}>
{page.users.map(user => (
<div key={user.id}>{user.name}</div>
))}
</Fragment>
))}
{/* Sentinel element: triggers load when visible */}
<div ref={ref}>
{isFetchingNextPage && 'Loading more...'}
{!hasNextPage && 'No more users'}
</div>
</div>
)
}
Multiple useQuery calls in the same component run in parallel automatically. For dynamic numbers of parallel queries, use useQueries.
// Two queries fire in parallel, no extra setup needed
function Dashboard() {
const usersQuery = useQuery({ queryKey: ['users'], queryFn: fetchUsers })
const statsQuery = useQuery({ queryKey: ['stats'], queryFn: fetchStats })
if (usersQuery.isLoading || statsQuery.isLoading) return <Spinner />
return (
<div>
<StatsPanel data={statsQuery.data} />
<UserTable data={usersQuery.data} />
</div>
)
}
// Dynamic number of parallel queries with useQueries
function MultiUserDetails({ userIds }: { userIds: number[] }) {
const results = useQueries({
queries: userIds.map(id => ({
queryKey: ['users', id],
queryFn: () => fetchUser(id),
})),
})
const allLoaded = results.every(r => r.isSuccess)
return allLoaded ? (
<ul>
{results.map((r, i) => (
<li key={userIds[i]}>{r.data?.name}</li>
))}
</ul>
) : <Spinner />
}
Prefetch data before the user navigates. If the request finishes before they arrive, the page renders from cache with no loading state. For the Next.js version, create the QueryClient inside the server component like below, never at module level, or cached data can leak between requests from different users.
// Prefetch on hover so data is ready when user clicks
function NavLink({ userId }: { userId: number }) {
const queryClient = useQueryClient()
const prefetchUser = () => {
queryClient.prefetchQuery({
queryKey: ['users', userId],
queryFn: () => fetchUser(userId),
staleTime: 1000 * 60, // don't refetch if already fresh
})
}
return (
<a
href={`/users/${userId}`}
onMouseEnter={prefetchUser} // prefetch on hover
>
View User
</a>
)
}
// Server-side prefetching with Next.js App Router
// app/users/page.tsx
import { dehydrate, HydrationBoundary, QueryClient } from '@tanstack/react-query'
export default async function UsersPage() {
const queryClient = new QueryClient()
await queryClient.prefetchQuery({
queryKey: ['users'],
queryFn: fetchUsers,
})
return (
<HydrationBoundary state={dehydrate(queryClient)}>
<UserList /> {/* renders with data already in cache */}
</HydrationBoundary>
)
}
TanStack Query vs Alternatives
All three solve the same core problem. The differences show up in bundle size, mutation ergonomics and how they fit into your existing state setup. Bundle sizes below are approximate and shift between releases.
| Feature | TanStack Query v5 | SWR | RTK Query |
|---|---|---|---|
| Bundle size (minzipped) | ~13 KB | ~4 KB | ~9 KB (part of RTK) |
| Mutations | First-class useMutation |
Manual (trigger fn) | First-class endpoints |
| Infinite queries | Built-in useInfiniteQuery |
Built-in useSWRInfinite |
Manual with serializeQueryArgs |
| Cache granularity | Per query key (flexible) | Per URL key | Per endpoint + args |
| Optimistic updates | Built-in with rollback | Via mutate(data, false) |
Built-in via onQueryStarted |
| DevTools | Excellent visual inspector | None official | Redux DevTools integration |
| Framework support | React, Vue, Solid, Angular | React only | React (via Redux) |
| Best for | Complex apps, multiple frameworks | Simple apps, minimal boilerplate | Redux-heavy codebases |
My rough rule: TanStack Query for features and DevTools, SWR when bundle size matters most and your needs are simple, RTK Query if the app already runs on Redux. For a new project with no Redux, I start with TanStack Query.
Error Handling & Retry Logic
Failed queries are retried 3 times by default with exponential backoff. You can change that globally or per query, and hand errors to an error boundary instead of checking isError everywhere.
One thing that trips people up: fetch doesn't reject on a 404 or 500. If your query function doesn't check res.ok and throw, the query "succeeds" with an error payload as its data, and no retry or error state ever kicks in. Also note that error.status in the example below only exists if your fetcher throws an error object that carries the status code.
// Per-query retry configuration
const { data, error } = useQuery({
queryKey: ['users'],
queryFn: fetchUsers,
retry: (failureCount, error) => {
// Don't retry on 404 or 401
if (error.status === 404 || error.status === 401) return false
return failureCount < 3
},
retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
})
// Global error handling with QueryCache
const queryClient = new QueryClient({
queryCache: new QueryCache({
onError: (error, query) => {
if (query.state.data !== undefined) {
// Only show toast if we had data (background refetch failure)
toast.error(`Background refresh failed: ${error.message}`)
}
},
}),
mutationCache: new MutationCache({
onError: (error) => {
toast.error(`Action failed: ${error.message}`)
},
}),
})
// Error boundary for declarative error handling
import { QueryErrorResetBoundary } from '@tanstack/react-query'
import { ErrorBoundary } from 'react-error-boundary'
function App() {
return (
<QueryErrorResetBoundary>
{({ reset }) => (
<ErrorBoundary
onReset={reset}
fallbackRender={({ resetErrorBoundary }) => (
<div>
<p>Something went wrong!</p>
<button onClick={resetErrorBoundary}>Try again</button>
</div>
)}
>
<UserList />
</ErrorBoundary>
)}
</QueryErrorResetBoundary>
)
}
Best Practices
Query Key Conventions
- Use arrays for all query keys:
['users'],['users', id],['users', { status: 'active' }] - Put the most general identifiers first and specific ones last. Invalidation matches by prefix, so this lets you target exactly what you need
- Extract key factories to avoid typos and ease invalidation:
userKeys.detail(id)
// Define all keys in one place
const userKeys = {
all: ['users'] as const,
lists: () => [...userKeys.all, 'list'] as const,
list: (filters: object) => [...userKeys.lists(), filters] as const,
details: () => [...userKeys.all, 'detail'] as const,
detail: (id: number) => [...userKeys.details(), id] as const,
}
// Usage: typo-safe, easy to invalidate
const { data } = useQuery({
queryKey: userKeys.detail(userId), // ['users', 'detail', 123]
queryFn: () => fetchUser(userId),
})
// Invalidate all user queries after a bulk action
queryClient.invalidateQueries({ queryKey: userKeys.all })
// Invalidate only a specific user's detail
queryClient.invalidateQueries({ queryKey: userKeys.detail(42) })
Don't put useQuery inside conditionals or loops. It breaks the Rules of Hooks, and React will complain that it "rendered more hooks than during the previous render". For conditional fetching, use the enabled option. For dynamic numbers of queries, use useQueries.
QueryClient Configuration Reference
| Option | Default | Recommendation |
|---|---|---|
staleTime |
0 (always stale) | Set to 1-5 min for most resources |
gcTime |
5 minutes | Leave default; increase for rarely changing data |
retry |
3 | Lower to 1-2 for user-triggered actions |
refetchOnWindowFocus |
true | Keep true for real-time-ish data; disable for static |
refetchOnReconnect |
true | Keep true; users expect fresh data after reconnect |
refetchInterval |
false | Set per-query for polling (e.g., live dashboards) |
When I'd use TanStack Query (and when I wouldn't)
I reach for it when a React app talks to an API from many screens, when the same data shows up in several components, or when users expect lists to update after they edit something. That's where hand-rolled useEffect fetching falls apart, and where the cache and invalidation model pays for itself. It also doesn't replace Zustand or useState; it takes server data off their plate so they only hold UI state.
I'd skip it in a few cases:
- Mostly static sites. If a page fetches once at build time or on the server and never changes on the client, the library adds bundle weight for nothing.
- Apps already on Redux Toolkit. RTK Query fits better there than running two caches side by side.
- Framework-owned data loading. If you're fully on React Server Components or Remix loaders and rarely refetch on the client, the framework already covers most of what you'd use it for.
- Real-time streams. For WebSocket-heavy data, TanStack Query can hold the result via
setQueryData, but it won't manage the connection for you.
Mistakes I see most often
- Leaving staleTime at 0. Every mount and window focus triggers a refetch. Pick a value per resource based on how often it really changes.
- Query keys missing a variable. If
queryFnusespageorfilterbut the key doesn't include it, you'll get the wrong cached data back. The official ESLint plugin (@tanstack/eslint-plugin-query) catches this. - Copying server data into useState. Then you have two sources of truth and the copy goes stale. Read from the query result directly.
- Skipping cancelQueries in optimistic updates. An in-flight refetch can land after your optimistic write and overwrite it, which looks like a flicker back to the old value.