What You'll Learn
- 1Explain what a query cache provides that a fetch inside an effect does not
- 2Design key hierarchies so related data can be invalidated precisely
- 3Choose stale time, refetch and retry settings per resource rather than globally
- 4Write an optimistic mutation with cancel, rollback and invalidation
Fetching data inside an effect is the first thing every React developer writes and the last thing a production app should keep. It works, then it grows a loading flag, an error object, a cancellation dance with AbortController, a duplicated request when two components mount together, a stale closure over a prop, and finally a second copy of the same fetch somewhere else in the tree because the screen needed the data too. A query cache is the generalisation: one place that owns keys, deduplication, retries, staleness and invalidation, so components simply read a value that is either fresh, about to be fresh, or failing with a reason.
What changes when the cache owns the request
The difference is less about convenience and more about correctness. Two components asking for the same resource issue one request instead of two. A component that unmounts mid-flight does not set state on a dead instance. A refocus of the window can trigger a background refresh without anyone writing a listener. And an error is data with a retry affordance attached rather than a boolean that a component must interpret.
| Concern | Fetch in an effect | Query cache |
|---|---|---|
| Duplicate requests | One per mount | Deduplicated by key |
| Cancellation | Manual cleanup every time | Owned by the cache |
| Staleness | Never; data is as old as the mount | Declared per key with stale time |
| Retry and backoff | Reimplemented | Built in and configurable |
| Sharing after unmount | Lost | Served from cache instantly |
| Invalidation after a write | Ad hoc refetch calls | Targeted key invalidation |
Keys are the schema of your cache
A key is not an arbitrary string; it is a structured description of the resource, usually an array of segments such as entity type, identifier, and any parameters that change the answer. Because keys are hierarchical, invalidation can target a prefix: invalidating every list of a type while leaving unrelated data untouched. Getting this right is most of cache design, and getting it wrong produces either stale lists that never update or refetch storms that hammer the server after every mutation.
import { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query';
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 30_000,
gcTime: 5 * 60_000,
retry: (failureCount, error) => error.status >= 500 && failureCount < 2,
refetchOnWindowFocus: true,
},
},
});
export function AppRoot({ children }) {
return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;
}
export function useProjects(teamId) {
return useQuery({
queryKey: ['projects', { teamId }],
queryFn: ({ signal }) => fetch('/api/projects?team=' + teamId, { signal }).then((res) => {
if (!res.ok) throw Object.assign(new Error('Request failed'), { status: res.status });
return res.json();
}),
select: (projects) => projects.filter((project) => !project.archived),
placeholderData: (previous) => previous,
enabled: Boolean(teamId),
});
}
Read the options as policy rather than as tuning knobs. Stale time says how long an answer is considered good enough to show without asking again; thirty seconds is generous for a dashboard and reckless for a trading screen. Placeholder data keeps the previous team's list on screen while the new one loads, which removes the flash of empty state without pretending the new data has arrived. Enabled prevents a request for an id that does not exist yet. Retry inspects the status so a four hundred is not retried while a five hundred is.
Staleness, refetch and the myths around them
Two misconceptions cause most misconfiguration. The first is that stale time equals cache time: it does not. Stale time decides when a mount triggers a background refetch; garbage collection time decides when unused data is evicted. A resource can be stale for an hour and still render instantly from memory while a background request refreshes it, which is exactly the behaviour users expect from a native app.
The second is that refetch on window focus is annoying. For read-only dashboards it is the feature. For a screen with a half-filled form overlaid on the data it causes surprising resets, so the setting belongs in per-query policy rather than in one global default. The same applies to refetch intervals: a live operations board might poll every five seconds while a settings page never polls at all, and neither should have to fight a global configuration.
Mutations that do not lie to the user
Optimistic updates are worth writing when the action is frequent, obvious and reversible â marking a task complete, starring a message, reordering a list. The pattern has three steps that must all be present: cancel any in-flight queries that would overwrite the optimistic value, apply the change to the cache directly, and keep the previous value so an error can roll it back exactly. Skipping the cancel step is the subtle bug, because a background refetch started a second earlier can land after your optimistic write and erase it before the user finishes looking.
import { useMutation, useQueryClient } from '@tanstack/react-query';
export function useToggleTask(listKey) {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ id, done }) =>
fetch('/api/tasks/' + id, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ done }),
}).then((res) => {
if (!res.ok) throw new Error('Update failed');
return res.json();
}),
onMutate: async ({ id, done }) => {
await queryClient.cancelQueries({ queryKey: listKey });
const previous = queryClient.getQueryData(listKey);
queryClient.setQueryData(listKey, (current) =>
(current || []).map((task) => (task.id === id ? { ...task, done } : task))
);
return { previous };
},
onError: (error, variables, context) => {
if (context && context.previous) {
queryClient.setQueryData(listKey, context.previous);
}
},
onSettled: (data, error, variables) => {
if (!error) {
queryClient.invalidateQueries({ queryKey: ['tasks'] });
queryClient.invalidateQueries({ queryKey: ['tasks', variables.id] });
}
},
});
}
Notice the ordering. Optimistic write first so the interface responds immediately, rollback on error so the cache never reflects a change the server rejected, and invalidation on success so the authoritative value replaces your guess. Invalidate broadly on success rather than surgically patching: the server may have normalised a field, adjusted a timestamp or recalculated a counter, and a local patch that assumes otherwise leaves the cache subtly wrong.
Keeping lists and details consistent
The classic inconsistency is completing a task and seeing it done in the list while the open detail panel still shows the old value, because the two screens use different keys and only one was updated. There are three ways to handle it and they are not equally good. Patching both keys manually works until a third screen appears. Invalidating a common prefix is the durable answer and is why keys should share a prefix that represents the entity family. Subscribing every screen to the same query key is the third option and the best one when the screens genuinely want the same data â a detail view and a list cell that show the same field should read the same query, not two that happen to hold equal values.
Dependent queries deserve mention because they break in a characteristic way. Two queries where the second needs the first's result should either be chained through a key that includes the first result, or run with enabled disabled until the dependency resolves. Otherwise the second fires with an empty id, caches a four hundred under that key, and keeps serving it after the real id arrives.
Memory, requests and the limits of caching
Caches are bounded on purpose. Garbage collection removes entries nothing has read for the configured window, which keeps a long session from accumulating every screen ever visited. Beyond that, watch for key explosion: a key containing a timestamp, a mouse position or a random id defeats deduplication entirely and turns the cache into a memory leak with a nice API.
Also decide what must never be cached. Payment responses, one-time tokens and anything with a short server-side lifetime should bypass the cache or use a zero stale time, because showing a stale success banner for a failed charge is a trust problem, not a performance one. The default should be that everything is cached deliberately, with explicit opt-outs where correctness demands it.
Common Mistakes
Putting a timestamp or random value in a query key so nothing is ever deduplicated
Fix: Use keys that describe the resource and its parameters, and nothing else
Applying an optimistic update without cancelling in-flight queries first
Fix: Cancel, then write, then keep the previous value for rollback
Patching one screen's key after a mutation and leaving siblings stale
Fix: Invalidate the shared entity prefix so every dependent view refetches
Setting one global stale time for resources with very different volatility
Fix: Keep a sensible default and override per query where freshness matters
Best Practices
- Model keys as structured arrays that share a prefix per entity family
- Treat stale time as freshness policy and garbage collection as memory policy
- Show placeholder data instead of a spinner when a previous result exists
- Invalidate broadly after a successful mutation rather than patching exact entries
- Opt out of caching explicitly for tokens, payments and other short-lived responses
Key Takeaways
- A query cache replaces hand-written loading, cancellation and deduplication with one owner
- Key hierarchy is cache design: prefix invalidation is what keeps lists and details consistent
- Staleness and eviction are different knobs with different consequences
- Optimistic updates need cancel, write, rollback and invalidate â all four steps
- Never cache secrets or one-time responses; cache everything else deliberately