Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 14.6 — Server State with TanStack Query
React · Example 2 of 3

useMutation, invalidateQueries and deduplication

Two components, one GET: requests for the same key are deduplicated. After the successful POST, invalidation triggers one new GET and both components update. The failed mutation leaves the cache alone.

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.

01

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.

02

Write a DeleteTodo button using useMutation that removes the todo from the ["todos"] cache with setQueryData on success.

03

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

01

What is the difference between server state and client state, and why does server state need a special tool?

02

Explain staleTime and gcTime and what happens when a component mounts with cached data in each case.

03

What is a query key and what rules should it follow?

04

Walk through what happens when a mutation succeeds and you call invalidateQueries.

05

What's the difference between isPending, isLoading and isFetching?

useMutation, invalidateQueries and deduplication

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

server: GET /todos
loaded: 1 todos | Learn Suspense
server: POST /todos ""
error: Title is required
server: POST /todos "Learn TanStack Query"
while saving: Adding...
server: GET /todos
after invalidate: 2 todos | Learn Suspense, Learn TanStack Query