Lesson 29 of 37React at scale
Server State with TanStack Query
Cache server data with TanStack Query v5: query keys and factories, staleTime vs gcTime, mutations with rollback, infinite lists, SSR hydration and tests.
A ticket lands in your sprint: "After I rename a project, the sidebar still shows the old name until I refresh. Also the projects page flashes a spinner every time I come back to it." You open the code and find three components each fetching the same project in their own useEffect, a hand-rolled loading flag in each, and no shared cache. None of this is a bug in one place. It is the cost of treating server data like local state. TanStack Query (v5, the current major for React) exists to make server data a cache with rules, and most frontend teams that do not use a framework's data layer use it or something like it. This lesson goes past the preview you saw in Data Fetching and into how the cache actually behaves, because that is what you will debug at work.
Server state is a cache, not state
In State Management at Scale you sorted state into kinds. Server state is the odd one out. You do not own it: someone else can change it at any moment. What you hold in the browser is a copy that is already going stale the moment it arrives. So the questions are cache questions. Is my copy fresh enough to show? When should I refetch? Two components want the same data, do I send two requests? I just changed it on the server, which copies are now wrong?
TanStack Query answers these with one object, the QueryClient. Inside it is a cache of queries, each stored under a query key. Every useQuery call is an observer that subscribes to one entry. The entry owns the data, the status, the timestamp of the last fetch, and the in-flight promise. Components never own the data. They just watch it.
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
const queryClient = new QueryClient({
defaultOptions: {
queries: { staleTime: 30_000 }, // a sensible app-wide default
},
});
createRoot(document.getElementById("root")!).render(
<QueryClientProvider client={queryClient}>
<App />
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>,
);Create the client once, outside any component (or inside useState(() => new QueryClient()) if it must live in a component). Creating it in a component body throws the whole cache away on every render. The Devtools panel shows every key, its status, and when it was last fetched. When someone says "the data is wrong", open it before you open the code. By default the Devtools are only bundled in development builds, so leaving them in main.tsx costs production nothing.
How the cache works, in 60 lines
The fastest way to understand the library is to build a tiny version. This one has a shared cache keyed by string, deduplication (two observers, one request), a staleTime so fresh data is not refetched, and stale-while-revalidate (stale data is shown while a background refetch runs). It uses useSyncExternalStore, the same hook real stores use to plug into React.
Click "Show both" a few times quickly, then wait three seconds and click it again. Watch the network counter.
Two components mounted, one request. Remount within three seconds, zero requests and no spinner. Remount later, the old data shows instantly with "(refreshing)" while a background fetch runs. That is the core of TanStack Query. The real library adds retries, garbage collection, focus and reconnect triggers, cancellation, structural sharing (unchanged parts of the new data keep their old object identity, so memoised children do not re-render), and a lot of edge-case handling. But the shape is exactly this.
Query keys and key factories
A query key is an array. TanStack Query hashes it deterministically, so ["todos", { status: "open", page: 2 }] and ["todos", { page: 2, status: "open" }] are the same key (object property order does not matter), while ["todos", 2] and [2, "todos"] are different (array order does). The rule that prevents most cache bugs: everything the query function uses must be in the key. If your fetch reads page but the key does not include it, page 2 overwrites page 1's entry, and you serve the wrong page from cache. The @tanstack/eslint-plugin-query package has an exhaustive-deps rule for exactly this.
Keys are also how you target the cache later, and matching works by prefix. Invalidating ["todos"] hits every key that starts with "todos". So on a real team you put keys in one place, ordered from general to specific, and pair them with queryOptions so the key and the function can never drift apart.
import { queryOptions } from "@tanstack/react-query";
export const todoKeys = {
all: ["todos"] as const,
lists: () => [...todoKeys.all, "list"] as const,
list: (filters: TodoFilters) => [...todoKeys.lists(), filters] as const,
detail: (id: number) => [...todoKeys.all, "detail", id] as const,
};
export const todoQueries = {
list: (filters: TodoFilters) =>
queryOptions({
queryKey: todoKeys.list(filters),
queryFn: ({ signal }) => api.getTodos(filters, { signal }),
}),
detail: (id: number) =>
queryOptions({
queryKey: todoKeys.detail(id),
queryFn: ({ signal }) => api.getTodo(id, { signal }),
staleTime: 60_000,
}),
};
// Anywhere in the app, all fully typed:
// useQuery(todoQueries.detail(7))
// queryClient.prefetchQuery(todoQueries.detail(7))
// queryClient.getQueryData(todoQueries.detail(7).queryKey) -> Todo | undefined
// queryClient.invalidateQueries({ queryKey: todoKeys.lists() }) -> every list, no detailsThe query function receives a context with a signal. Pass it to fetch and TanStack Query can cancel requests nobody is waiting for any more, which is the AbortController pattern from Data Fetching without the boilerplate. And remember the fetch gotcha: a 404 resolves, so your API helper must throw on !res.ok, or the query "succeeds" with an error body as data.
staleTime, gcTime and when refetches happen
These two settings are the most misunderstood part of the library, and a favourite interview question.
staleTime(default0): how long fetched data counts as fresh. Fresh data is served from cache with no request. Once stale, data is still shown, but certain triggers cause a background refetch.gcTime(default 5 minutes): how long an entry stays in memory after its last observer unmounts. While at least one component uses a key, it is never collected. In v4 this option was calledcacheTime. The rename togcTimein v5 happened precisely because people confused it with freshness.
The background refetch triggers, all on by default and all applying only to stale queries: a new component mounts using the key (refetchOnMount), the window regains focus (refetchOnWindowFocus), and the network reconnects (refetchOnReconnect). Failed queries also retry 3 times with exponential backoff before showing an error.
0s
First mount: fetch
No entry yet. `status` is `pending`, the request goes out, the data arrives and is fresh.
10s
Second component mounts
Data is fresh. Served from cache, no request.
40s
User refocuses the tab
Data is now stale. The old data stays on screen while a background refetch runs. `isFetching` is true, `isPending` is not.
1m
Both components unmount
The entry becomes inactive. The gcTime countdown of 5 minutes starts.
3m
User navigates back
Entry still in memory: instant render with the cached data, plus a background refetch because it is stale.
9m
Garbage collected
No observer for 5 minutes, so the entry is deleted. The next mount starts from `pending` with a spinner.
The most common complaint from a new team member is "it refetches every time I switch tabs, let's turn off refetchOnWindowFocus". Usually the real fix is a sensible staleTime. With the default of 0, every piece of data is stale immediately, so every trigger refetches. Decide per resource how stale is acceptable: a user's profile can be fresh for minutes, stock levels for seconds.
v5 also renamed the loading flags, which trips up anyone reading old blog posts. isPending means "no data yet" (status === "pending"). isFetching means "a request is in flight", including background refetches. isLoading is now isPending && isFetching: the first load, actually happening.
Match each v5 flag or option to what it tells you or controls.
Shaping queries: enabled, select, placeholderData
Three options cover most real screens.
import { keepPreviousData, useQuery } from "@tanstack/react-query";
// Dependent query: wait until we know the user.
const { data: user } = useQuery(userQueries.me());
const { data: projects } = useQuery({
...projectQueries.forOwner(user?.id ?? 0),
enabled: !!user, // does not run (and is not pending forever) until user exists
});
// Derive from the cache: this component re-renders only when the count changes.
const { data: openCount } = useQuery({
...todoQueries.list(filters),
select: (todos) => todos.filter((t) => !t.done).length,
});
// Paging without a spinner between pages.
const { data, isPlaceholderData } = useQuery({
...todoQueries.list({ ...filters, page }),
placeholderData: keepPreviousData,
});
// Disable "Next" while isPlaceholderData is true, so users cannot skip ahead of the data.select runs per observer, so two components can read different slices of one cached response. Define it outside the component (or memoise it) if it is expensive, because an inline function runs again on every render. placeholderData is not written to the cache. That is the difference from initialData, which is stored and treated as real data with its own freshness. Use initialData only when you genuinely have the full data already, for example from a list response.
Mutations, invalidation and optimistic updates
Writes go through useMutation. After a write, the cache has wrong copies, and you have two ways to fix them:
- Invalidate:
queryClient.invalidateQueries({ queryKey: todoKeys.lists() })marks matching entries stale and refetches the ones on screen. Simple and always correct, at the cost of a request. - Write directly:
queryClient.setQueryData(key, updater)when the server response already contains the new truth (aPATCHthat returns the updated todo). No extra request.
If onSuccess or onSettled returns the invalidation promise, the mutation stays pending until the refetch finishes, so your "Saving..." button does not flip back while stale data is still on screen.
For instant feedback, update the cache before the server answers, and roll back if it fails:
export function useToggleTodo(filters: TodoFilters) {
const queryClient = useQueryClient();
const key = todoKeys.list(filters);
return useMutation({
mutationFn: (todo: Todo) => api.updateTodo(todo.id, { done: !todo.done }),
onMutate: async (todo) => {
await queryClient.cancelQueries({ queryKey: key }); // stop a refetch overwriting us
const previous = queryClient.getQueryData<Todo[]>(key);
queryClient.setQueryData<Todo[]>(key, (old = []) =>
old.map((t) => (t.id === todo.id ? { ...t, done: !t.done } : t)),
);
return { previous }; // passed to onError and onSettled
},
onError: (_error, _todo, context) => {
queryClient.setQueryData(key, context?.previous); // roll back
toast.error("Could not update the task");
},
onSettled: () => queryClient.invalidateQueries({ queryKey: todoKeys.lists() }),
});
}onMutate runs first. It cancels in-flight refetches of the list, so a slow old response cannot land on top of the optimistic one.
Here is that flow stripped down so you can watch the snapshot do its job. Note that every update creates a new array and new objects.
Press Run (⌘ Enter) to see what happens.A teammate writes the optimistic update by mutating in place. The server rejects the toggle. What does the last line print?
const cache = new Map([["todos", [{ id: 2, done: false }]]]);
const previous = cache.get("todos"); // snapshot
cache.get("todos").forEach((t) => { // "optimistic" update, in place
if (t.id === 2) t.done = true;
});
// server says no
cache.set("todos", previous); // rollback
console.log(cache.get("todos")[0].done);TanStack Query or useOptimistic? You met React's useOptimistic in Actions and Optimistic UI. It shows a temporary value inside one component tree while an Action runs, and reverts by itself when the Action ends. That is perfect when the optimistic value only matters where the form is. Cache-level updates, as above, change every component that reads the key: the sidebar count, the header badge, the list. Use the one that matches where the data is shown. There is also a lighter TanStack option: render mutation.variables as a pending row while mutation.isPending, without touching the cache at all.
Infinite lists and Suspense
Feeds and "load more" lists use useInfiniteQuery. The cache entry holds an array of pages, and you tell it how to find the next page from the last one. In v5, initialPageParam is required.
const feed = useInfiniteQuery({
queryKey: ["feed"],
queryFn: ({ pageParam, signal }) => api.getFeed({ cursor: pageParam, signal }),
initialPageParam: null as string | null,
getNextPageParam: (lastPage) => lastPage.nextCursor ?? undefined, // undefined means no more pages
maxPages: 10, // optional: cap memory on very long feeds
});
const items = feed.data?.pages.flatMap((p) => p.items) ?? [];
// feed.fetchNextPage(), feed.hasNextPage, feed.isFetchingNextPageOne cost to know: when an infinite query refetches, it refetches every loaded page, one after another, so the pages stay consistent. Fifty loaded pages means fifty requests on a focus refetch. maxPages and a longer staleTime keep that sane.
useSuspenseQuery plugs into the Suspense model from Transitions and Suspense. The component suspends until data exists, so data is always defined and the type has no undefined. Loading UI comes from the nearest <Suspense> and errors go to the nearest error boundary. It does not accept enabled or placeholderData. Watch for a hidden waterfall: two useSuspenseQuery calls in one component run one after the other, because the first suspends before the second is reached. Use useSuspenseQueries for parallel fetches, or prefetch both higher up.
Prefetching and SSR hydration in Next.js
Starting a fetch before the component needs it removes waiting. queryClient.prefetchQuery(todoQueries.detail(id)) in an onMouseEnter or onFocus handler means the detail page usually renders from cache. Route loaders, which you will see in Client-Side Routing, do the same at navigation time.
In the Next.js App Router you can prefetch on the server and hand the cache to the client. Two rules matter. First, on the server, create a new QueryClient for every request. A module-level client on the server is shared between all users, so one user's data can be served to another. Second, set a staleTime above zero, or the client refetches immediately on hydration and you paid for the server fetch for nothing.
import { isServer, QueryClient } from "@tanstack/react-query";
function makeQueryClient() {
return new QueryClient({ defaultOptions: { queries: { staleTime: 60_000 } } });
}
let browserClient: QueryClient | undefined;
export function getQueryClient() {
if (isServer) return makeQueryClient(); // fresh per request: never share users' data
return (browserClient ??= makeQueryClient()); // one client for the browser's lifetime
}import { dehydrate, HydrationBoundary } from "@tanstack/react-query";
import { getQueryClient } from "../get-query-client";
import { todoQueries } from "@/features/todos/queries";
import { TodoList } from "./todo-list"; // a "use client" component calling useQuery(todoQueries.list(...))
export default async function TodosPage() {
const queryClient = getQueryClient();
await queryClient.prefetchQuery(todoQueries.list({ status: "open" }));
return (
<HydrationBoundary state={dehydrate(queryClient)}>
<TodoList />
</HydrationBoundary>
);
}The QueryClientProvider itself lives in a small "use client" providers component in the root layout. The TanStack docs also show how to stream pending queries without awaiting them; check the Advanced Server Rendering guide for the current options, as they have evolved during v5.
const queryClient = new QueryClient() to the top of a module that both the server and client import, to avoid creating it twice. What is the worst consequence?Testing queries
Two rules keep tests reliable. Give every test a fresh QueryClient, so cached data from one test cannot make another pass or fail depending on order. And turn retries off, or a test of the error state waits through three retries with backoff and times out.
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { render } from "@testing-library/react";
export function renderWithClient(ui: React.ReactElement) {
const client = new QueryClient({
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
});
return { client, ...render(<QueryClientProvider client={client}>{ui}</QueryClientProvider>) };
}Mock the network, not the hook. As you saw in Testing React, MSW intercepts fetch at the network layer, so your query functions, keys and error handling all run for real. Then assert with findByText, which waits for the async render. Mocking useQuery itself tests nothing you shipped.
Put the steps of a correct optimistic update in order.
- Tap the steps below in the right order.
When not to use it
TanStack Query is a client-side cache. If a client cache is not the problem, it is weight you do not need.
- Server Components fetching for display. A Next.js page that renders a list and never refetches it in the browser can
awaitthe data on the server. No client cache required. - One request, one screen, no sharing. A settings page loaded once is fine with a loader or a small effect.
- Client state. Modal open, selected tab, form drafts. That belongs in component state, the URL, or a client store. Putting it in the query cache because it is "global" is a common mistake.
Where it shines: dashboards with many widgets on shared data, lists with optimistic edits, polling (refetchInterval), infinite scroll, and any SPA without a framework data layer. Many teams combine it with router loaders: the loader calls queryClient.ensureQueryData so navigation starts the fetch, and the component reads the same entry with useQuery.
- server state
- Data whose source of truth is a server. The client holds a cached copy that can go stale at any time.
- QueryClient
- The object holding the query and mutation caches. Create one per browser session, and one per request on a server.
- query key factory
- One module that builds query keys from general to specific, often paired with
queryOptions, so keys never drift between files. - staleTime
- How long fetched data is fresh. Fresh data is served with no request. Default 0.
- gcTime
- How long an unused cache entry stays in memory after its last observer unmounts. Default 5 minutes. Called
cacheTimebefore v5. - invalidation
- Marking cache entries stale by key prefix so the ones on screen refetch, usually after a mutation.
- HydrationBoundary
- Component that takes a dehydrated server cache and puts it into the client QueryClient, so the first client render has the data.