TanStack Query
A server-state layer on TanStack Query v5: domain-shaped keys, colocated query functions, optimistic mutations, targeted invalidation, and every loading, error, empty and stale state.
Skills
What it sets up
Data the API owns lives in the TanStack Query cache, and only there. The cache fetches, dedupes, refetches and invalidates it; components just say what they need. What’s left for React state or a store is genuinely client state: a modal, a draft, a theme.
The skill sets up one QueryClient with sane defaults, then per domain: key factories shaped like the data, queryOptions that keep each key next to its fetcher, and mutations that update optimistically and invalidate only what they changed.
Why teams choose it
- Server state isn't client stateAPI data goes stale and changes elsewhere. Kept in Redux or Context, every endpoint needs hand-written loading, error, caching and refetch code.
- Caching and dedupingTen components asking for one key make one request. Going back to a screen shows cached data at once.
- Stale-while-revalidateData shows immediately and refreshes quietly on mount, focus and reconnect, so spinners are rare.
- Precise invalidationHierarchical keys let one write refresh exactly the queries it touched, and nothing else.
- Optimistic, with rollbackThe UI changes instantly, and quietly undoes itself if the server says no.
- Every state modelledPending, error, fetching, placeholder and refetch-error are separate, so the UI can be honest about each.
- No race conditionsEvery fetch gets an AbortSignal. Superseded and out-of-order responses never overwrite newer data.
- Typed end to endqueryOptions carries the data type with the key, into useQuery, prefetchQuery and getQueryData alike.
- DevtoolsEvery cache entry, its key, freshness and observers, visible. Cache bugs stop being guesswork.
Targeted invalidation
["tasks","list",{"projectId":"p1"},{}]cached["tasks","list",{"projectId":"p1"},{"status":"done"}]cached["tasks","list",{"projectId":"p2"},{}]cached["tasks","detail","t1"]cached["tasks","detail","t9"]cached["projects","detail","p1"]cached
Pick a write to see which cache entries it touches.
Every state, handled
| Query says | Means | QueryState shows |
|---|---|---|
| isPending | Nothing cached yet | Skeleton |
| isError, no data | Failed, nothing to show | Message + retry |
| empty data | Loaded, nothing there | Empty state |
| isFetching | Refreshing in the background | Keep data, quiet indicator |
| isPlaceholderData | Old filter's rows while new load | Keep rows, mark as loading |
| isRefetchError | Refresh failed, old data kept | Show data + "couldn't refresh" |
Files it creates
src/features/tasks/task.queries.ts
import { keepPreviousData, queryOptions } from "@tanstack/react-query";
import { taskApi } from "./task.api";
import type { TaskFilters } from "./task.types";
// Keys shaped like the domain, broad to narrow, so one prefix reaches exactly
// the entries a write affects:
// ["tasks"] every task query
// ["tasks", "list"] every list
// ["tasks", "list", { projectId }] one project's lists (any filter)
// ["tasks", "list", { projectId }, filters] one filtered list
// ["tasks", "detail", id] one task
export const taskKeys = {
all: ["tasks"] as const,
lists: () => [...taskKeys.all, "list"] as const,
projectLists: (projectId: string) => [...taskKeys.lists(), { projectId }] as const,
list: (projectId: string, filters: TaskFilters = {}) => [...taskKeys.projectLists(projectId), filters] as const,
details: () => [...taskKeys.all, "detail"] as const,
detail: (id: string) => [...taskKeys.details(), id] as const,
};
// Key and function side by side, so they can't drift apart. Use the same
// options in useQuery, useSuspenseQuery, prefetchQuery and getQueryData:
// the data type travels with the key.
export const taskQueries = {
list: (projectId: string, filters: TaskFilters = {}) =>
queryOptions({
queryKey: taskKeys.list(projectId, filters),
queryFn: ({ signal }) => taskApi.list(projectId, filters, signal),
// Changing a filter keeps the old rows on screen until the new ones
// arrive, instead of flashing back to a skeleton.
placeholderData: keepPreviousData,
}),
detail: (id: string) =>
queryOptions({
queryKey: taskKeys.detail(id),
queryFn: ({ signal }) => taskApi.get(id, signal),
staleTime: 30_000,
}),
};