useQuery: caching, staleTime and background refetch
Shown again, both have data instantly from the cache, with no loading state. The stale one refetches in the background (call 3) and updates; the fresh one makes no request.
TanStack Query keeps server data in a shared cache identified by query keys: useQuery reads it (with isPending, isFetching and error), staleTime decides when data needs refreshing and gcTime when unused data is deleted, and useMutation plus invalidateQueries change data on the server and refresh every screen that shows it.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write a useProduct(id) hook with TanStack Query that caches each product for 5 minutes as fresh and doesn't run when id is null.
Write a DeleteTodo button using useMutation that removes the todo from the ["todos"] cache with setQueryData on success.
A search page queries ["search", term]. Each keystroke shows a loading state. Make it keep the previous results while the next ones load.
Explain it without notes
What is the difference between server state and client state, and why does server state need a special tool?
Explain staleTime and gcTime and what happens when a component mounts with cached data in each case.
What is a query key and what rules should it follow?
Walk through what happens when a mutation succeeds and you call invalidateQueries.
What's the difference between isPending, isLoading and isFetching?
Preview
Console
Nothing logged yet.Expected console output
server: fetch user 1 (call 1)
server: fetch user 1 (call 2)
first render: stale at once: Loading... | fresh 1 min: Loading...
loaded: stale at once: Asha from call 1 | fresh 1 min: Asha from call 2
server: fetch user 1 (call 3)
shown again: stale at once: Asha from call 1 (refreshing) | fresh 1 min: Asha from call 2
after refetch: stale at once: Asha from call 3 | fresh 1 min: Asha from call 2