If you have ever fetched data inside a useEffect, stored it in useState, and then watched the same request fire again on every page visit, every tab switch, and every component remount, you already know the problem TanStack Query solves. It is not another state library. It is a server-state library: it fetches your data, caches it, keeps it fresh in the background, and stops you writing the loading, error, retry, and refetch logic by hand for the hundredth time. This guide shows you how to use it properly in React, with the defaults that matter and the mistakes to avoid. It is written against the current TanStack Query (v5) documentation, verified on 18 November 2026.
What TanStack Query actually solves
Client state and server state are different problems, and the official docs make the distinction sharply. Client state is yours: a modal open flag, a form draft, a theme choice. You control it, it lives in your app, and it only changes when your code changes it.
Server state is none of those things. It lives on a server you may not control, it arrives asynchronously, it can be changed by other people without your app knowing, and it can go out of date at any moment. That is why hand-rolled fetching always grows the same messy tail: caching, deduplicating identical requests, refetching stale data in the background, handling pagination, and cleaning up memory when a component unmounts.
TanStack Query takes that whole tail off your hands. You describe a query — what to fetch and what uniquely identifies it — and the library handles the cache, the background refetches, and the loading and error states. Your job shrinks to two things: choosing good query keys and choosing sensible freshness settings. Everything else in this post is detail on those two jobs.
Install TanStack Query and wire up the provider
Install the React package, plus the devtools package while you are learning. The devtools panel shows every query, its key, and whether it is fresh or stale, which turns cache behaviour from a mystery into something you can watch.
npm install @tanstack/react-query
npm install -D @tanstack/react-query-devtools
Create one QueryClient and wrap your app in QueryClientProvider. Create it outside your component — if you create it inside a render function, you get a fresh client (and an empty cache) on every render, which defeats the whole point.
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 60 * 1000,
},
},
})
export function App() {
return (
<QueryClientProvider client={queryClient}>
<PostsPage />
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
)
}
Setting a global staleTime of one minute here is a deliberate choice, not a copy-paste habit. You will see why in the staleTime section below. For now, notice the shape: one client, one provider, sensible defaults in one place, overrides per query where a specific screen needs them.
Your first useQuery in TanStack Query
A query needs exactly two things: a queryKey and a queryFn. The key identifies the data in the cache. The function returns a promise that resolves with the data or throws an error. If your function returns a failed HTTP response as if it were data, TanStack Query cannot know anything went wrong — so throw on a non-OK response.
import { useQuery } from '@tanstack/react-query'
async function getPosts() {
const response = await fetch('/api/posts')
if (!response.ok) {
throw new Error(`HTTP ${response.status}`)
}
return response.json()
}
export function PostsPage() {
const { data, isPending, isError, error, isFetching } = useQuery({
queryKey: ['posts'],
queryFn: getPosts,
})
if (isPending) return <p>Loading posts…</p>
if (isError) return <p>Could not load posts: {error.message}</p>
return (
<div>
{isFetching && <p>Refreshing…</p>}
<ul>
{data.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
)
}
The three status flags here are not interchangeable, and mixing them up is the most common beginner bug. isPending means there is no cached data and no fetch attempt has finished yet — this is your first-load spinner. isFetching means the query function is executing right now, including background refetches, so it is the right flag for a subtle “refreshing” indicator while old data stays on screen. isLoading is the combination of the two: the first fetch is in flight. And isRefetching is a background refetch in flight, which by definition excludes the initial load.
That distinction is the whole UX win. With hand-rolled fetching, a refetch usually means a full-screen spinner again. With TanStack Query, a stale query shows its cached data immediately and refetches quietly underneath it. Your users see content, not spinners.
Query keys are the cache
If you remember one sentence from this post, make it this one: the query key is the cache entry. Two components using the same key share one fetch, one cache entry, and one background refetch. Change any part of the key and you get a different cache entry, which is exactly how pagination, filtering, and detail pages should work.
// A list
useQuery({ queryKey: ['posts'], queryFn: getPosts })
// The same list, filtered
useQuery({
queryKey: ['posts', { status: 'published', page: 2 }],
queryFn: () => getPosts({ status: 'published', page: 2 }),
})
// One item from that list
useQuery({
queryKey: ['posts', postId],
queryFn: () => getPost(postId),
})
Three rules keep keys sane. First, keys are arrays, and the first element is usually the resource name. Second, put every variable the fetch depends on into the key — if the page number or filter lives outside the key, two different screens will share (and overwrite) one cache entry. Third, keep keys serialisable: strings, numbers, and plain objects. The library hashes keys into a stable string, so object property order does not matter, but functions, class instances, and dates-as-objects in keys will bite you.
For a real app, use a key factory — a small object of functions that build keys in one place — instead of scattering string literals across components. When you later need to invalidate “everything about posts”, you invalidate the ['posts'] prefix once, and every list, filter, and detail query under it refetches. If your keys are ad-hoc strings, that one-line invalidation becomes a search through the whole codebase.
export const postKeys = {
all: ['posts'],
lists: () => [...postKeys.all, 'list'],
list: (filters) => [...postKeys.lists(), filters],
detail: (id) => [...postKeys.all, 'detail', id],
}
TanStack Query staleTime vs gcTime: the two knobs everyone confuses
staleTime and gcTime sound similar and do completely different jobs. Confusing them is why so many TanStack Query apps either refetch constantly or serve ancient data.
staleTime is how long fetched data counts as fresh. The default is 0, which means data is stale the instant it arrives. That is why a default-configured app refetches on every component mount and every window-focus return: the data is always stale, so every trigger refetches. Set staleTime to match how fast the data actually changes — seconds for a live order status, minutes for a post list, hours for a country list, Infinity for data that effectively never changes.
gcTime is how long an unused cache entry stays in memory after the last component using it unmounts. The default is five minutes (or Infinity during server rendering). After that, the entry is garbage-collected and the next mount fetches from scratch. A query can therefore be stale and still cached, or fresh at the moment its last user unmounts. The two timers are independent.
useQuery({
queryKey: ['posts'],
queryFn: getPosts,
staleTime: 5 * 60 * 1000, // fresh for 5 minutes: no background refetch
gcTime: 30 * 60 * 1000, // kept in memory for 30 minutes after unmount
})
The refetch triggers then make sense. With the defaults, a query refetches on mount if its data is stale, on window focus if its data is stale, and on reconnect if its data is stale. If you find yourself turning those triggers off one by one, stop: what you almost always want is a longer staleTime, not disabled refetching. And note the retry defaults while you are here: failed queries retry three times on the client and zero times on the server, with exponential backoff capped at 30 seconds. For a definite 404 or 401, retrying is wasted work — pass a retry function that returns false for those statuses and only retries transient failures.
Mutations: change data, then invalidate
Queries read. Mutations write. useMutation takes a mutationFn and lifecycle callbacks, and the simplest correct pattern after a successful write is invalidation: tell TanStack Query that the affected keys are stale, and let it refetch them.
import { useMutation, useQueryClient } from '@tanstack/react-query'
export function NewPostForm() {
const queryClient = useQueryClient()
const createPost = useMutation({
mutationFn: async (post) => {
const response = await fetch('/api/posts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(post),
})
if (!response.ok) throw new Error(`HTTP ${response.status}`)
return response.json()
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['posts'] })
},
})
return (
<button
onClick={() => createPost.mutate({ title: 'Hello' })}
disabled={createPost.isPending}
>
{createPost.isPending ? 'Saving…' : 'Publish'}
</button>
)
}
Start with invalidation everywhere. It is one line, it is always correct, and it costs one refetch. Only reach for direct cache updates (setQueryData) where that refetch is visibly slow — for example, updating a detail view from the exact object the server just returned. Hand-updating lists is where bugs hide: sorting, filtering, and server-derived fields are easy to get wrong by hand and free when you refetch.
Two smaller mutation habits pay off immediately. Disable the submit button while isPending is true, or a double-click creates a duplicate. And keep mutation error handling in the component that owns the form, where you can show the message next to the field that caused it, rather than in a global handler that cannot.
Optimistic updates without lying to the user
An optimistic update changes the UI before the server confirms the write, so a frequent action like favouriting a post feels instant. The official docs describe two approaches: render the pending mutation’s variables directly in the UI (simpler, no cache surgery, no rollback code), or update the cache in onMutate with a rollback on error (better when several places on screen must reflect the change at once). The cache approach follows a strict four-step pattern — skip a step and you will ship a bug that only appears on a failed request.
const queryClient = useQueryClient()
const favouriteMutation = useMutation({
mutationFn: setFavourite,
onMutate: async ({ postId, favourite }) => {
const key = ['posts', 'detail', postId]
// 1. Stop an in-flight refetch overwriting your optimistic value
await queryClient.cancelQueries({ queryKey: key })
// 2. Snapshot the current value
const previous = queryClient.getQueryData(key)
// 3. Write the optimistic value
queryClient.setQueryData(key, (old) => ({ ...old, favourite }))
// 4. Return the snapshot so onError can restore it
return { key, previous }
},
onError: (_error, _variables, context) => {
queryClient.setQueryData(context.key, context.previous)
},
onSettled: (_data, _error, variables) => {
queryClient.invalidateQueries({
queryKey: ['posts', 'detail', variables.postId],
})
},
})
Notice the last step: whether the mutation succeeded or failed, the query is invalidated and refetched, so the UI ends up showing the server’s truth either way. And choose optimistic updates carefully. A favourite button is a good candidate; a payment, an inventory decrement, a permission change, or a destructive delete is not. For those, the user should wait for server confirmation before the UI claims success.
Pagination, infinite lists, and dependent queries
For numbered pagination, put the page in the query key and pass placeholderData: keepPreviousData. The previous page stays visible while the next page loads, instead of flashing a spinner on every page change. The placeholder flag on the result (isPlaceholderData) tells you when the data on screen belongs to the previous page, if you want to dim it.
import { useQuery, keepPreviousData } from '@tanstack/react-query'
const { data, isPlaceholderData } = useQuery({
queryKey: ['posts', { page }],
queryFn: () => getPosts({ page }),
placeholderData: keepPreviousData,
})
For infinite scroll, use useInfiniteQuery instead of hand-rolling page state. It tracks pages, fetches the next one on demand, and caches each page separately. You supply initialPageParam and a getNextPageParam function that reads the cursor or page number out of the last fetched page, and you can cap memory with maxPages so a long scroll session does not accumulate pages forever.
For dependent queries — a query that needs another query’s result first — gate the second query with enabled. A post list that needs a user ID first becomes enabled: !!user?.id, and the query simply does not run until the ID exists. One subtlety from the official docs: in that disabled state, use isLoading (first fetch in flight) rather than isPending for your loading UI, so a query that has not started yet does not show a spinner. The same enabled pattern covers feature flags, route parameters that may be absent, and any “only fetch this after that” chain.
Two more tools round out the set. select transforms the data a component receives without changing what is stored in the cache — derive a list of names from a list of users, and the component only re-renders when the selected output changes. And queryClient.prefetchQuery lets you fetch the next page, or the detail view behind a link, on hover, so navigation feels instant. Prefetching is the cheapest perceived-performance win in the whole library; use it for the one or two destinations users actually go to next, not for everything.
Seven TanStack Query mistakes to stop making
First, putting client state in the query cache. A modal flag or a form draft is not server state, and stuffing it into a query key means it gets refetched, garbage-collected, and invalidated by rules written for server data. Keep it in useState or a small client-state store.
Second, query keys that omit a variable. If the filter is not in the key, two filtered views share one cache entry and show each other’s data. If the page is not in the key, pagination silently overwrites itself.
Third, a global staleTime: Infinity. It feels fast because nothing ever refetches — until a user stares at data that changed an hour ago and blames your app. Reserve Infinity for genuinely static data.
Fourth, fetching in useEffect alongside TanStack Query in the same component. You now have two caches, two loading states, and a race. Move the fetch into a query and delete the effect.
Fifth, optimistic updates for irreversible actions, as covered above. Instant is not always honest.
Sixth, ignoring the devtools. When a query behaves strangely, the devtools panel answers in seconds whether the key is wrong, the data is stale, or the query is disabled. Guessing from console logs takes ten times longer.
Seventh, creating the QueryClient inside a component, or inside a Next.js server component without the proper provider boundary. A client created per render has no cache at all. Create it once, at module level for a plain React app, and follow the framework’s provider pattern for Next.js, where the server prefetches and dehydrates the cache and the client hydrates it through a boundary component.
When not to use TanStack Query
Not every fetch needs a cache. A one-off request on a rarely visited settings page is fine with a plain fetch. Real-time data over a WebSocket does not fit the request-response cache model either — use the socket directly and update the cache manually where a query displays that data. And if your app is already a Next.js app server-components project where the framework handles data fetching and caching for a page (see our guide to Next.js caching), TanStack Query belongs on the interactive, client-side parts, not as a second cache fighting the first. The same “one cache per concern” thinking applies to performance work generally — see our guide to using the React Profiler before you optimise a fetch that was never the bottleneck.
The 10-minute TanStack Query checklist
Install the package and the devtools, create one client outside any component, and wrap the app in the provider. Convert your first useEffect fetch to useQuery with a key that includes every variable the fetch depends on. Set staleTime per query to match how fast that data changes, and leave gcTime at its five-minute default until you have a reason to change it. Convert your first form submit to useMutation with invalidation on success, and only add an optimistic update where the action is frequent and reversible. Then open the devtools, click around, and watch the cache do what your hand-rolled code used to do — badly, and in ten times the lines.
Further Reading & References
- TanStack Query React docs — Overview (server state vs client state)
- TanStack Query React docs — useQuery reference (staleTime, gcTime, retry, refetch options, result flags)
- TanStack Query React docs — Optimistic Updates guide
- Flavio Copes — Introduction to TanStack Query (staleTime, gcTime, retries, optimistic updates)
- Stacknotice — TanStack Query v5 Complete Guide (2026)
- MefjuDev — TanStack Query Is the Last State Library Your React App Needs
- Tech Insider — React vs Vue Data Fetching: TanStack Query vs Pinia Colada (2026)
- DEV — Mastering useQuery: The Complete Dev Guide (TanStack React Query)



