State management and data fetching · senior
TanStack Query: server state as a cache
TanStack Query (v5) treats server data as a cache keyed by the query key: it dedupes requests, shows cached data instantly, refetches stale data in the background, retries failures, and lets you invalidate or optimistically update entries after mutations.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- The query key is like a dependency array: put every variable the query function uses in it; when the key changes, it fetches the new entry.
staleTime(default 0) = how long data counts as fresh; fresh data is served from cache with no request.gcTime(default 5 minutes, calledcacheTimebefore v5) = how long an unused query stays in memory.- Defaults: stale queries refetch on mount, window refocus and reconnect; failed queries retry 3 times with exponential backoff; results are structurally shared so unchanged data keeps its reference.
- Mutations: after success,
invalidateQueries({ queryKey: ["todos"] })(prefix match) orsetQueryDatawith the server response. - Optimistic updates: in
onMutatecancel queries, snapshotgetQueryData,setQueryData; restore inonError; invalidate inonSettled. Or render pending items from the mutationvariableswithout touching the cache. - Do not copy query data into
useState(it stops receiving updates) and do not use the cache as a client-state store. - RTK Query is the Redux-native alternative: endpoints, generated hooks, tag-based invalidation (
providesTags/invalidatesTags), OpenAPI codegen. - With Server Components, initial data can come from the server; client libraries handle interactive, polling and infinite parts (prefetch + hydrate).
The red pen
Common traps: mistake → fix
Mistake: "
staleTimeandgcTimeare the same thing"Fix: freshness vs memory lifetime.
Mistake: "Mirror server data into Redux slices by hand"
Fix: you rebuild a cache without invalidation.
Mistake: "Set a huge
gcTimeto avoid refetches"Fix:
staleTimecontrols refetching.
Easy to hard
Questions interviewers ask, easy to hard
- Defend TanStack Query (or RTK Query) over Context +
useEffectfor server data. - Explain
staleTimevsgcTime. - Invalidation after a mutation: query keys vs RTK Query tags.
- Implement optimistic updates with rollback.
- In a Next.js App Router app with Server Components, do you still need it?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.