TanStack Query part 2
Reading data is only half of server state. TanStack Query part 2 covers changing data with useMutation, telling the cache about it with invalidateQueries, optimistic updates with rollback, and paginated "Load more" lists with useInfiniteQuery.
49.1 Why is it used?
- Calling postTodo directly succeeds on the server (3 todos) but the screen still shows Todos: 2.
- The query cache was never told the server data changed, so nothing refetches.
- We need a way to send the request and then mark the old cached data as stale.
React (JSX)
function Todos() { const { data = [] } = useQuery({ queryKey: ["todos"], queryFn: getTodos, }); async function add() { await postTodo("Milk"); } return ( <> <button onClick={add}>Add</button> <p>Todos: {data.length}</p> </> );}Output
-- initial --[button] AddTodos: 2 -- after clicking Add (server now has 3) --[button] AddTodos: 249.2 useMutation: changing data
- useMutation takes a mutationFn that sends the POST.
- Unlike useQuery it never runs by itself: the request goes out only when you call mutate().
- isPending is true while it runs, so the button is disabled and shows Saving...
- Without invalidation the list still says Todos: 2 afterwards.
React (JSX)
function AddTodo() { const { mutate, isPending } = useMutation({ mutationFn: postTodo, }); return ( <button disabled={isPending} onClick={() => mutate("Milk")}> {isPending ? "Saving..." : "Add"} </button> );}Output
-- initial --[button] AddTodos: 2 -- request running --[button] Saving...Todos: 2 -- request done --[button] AddTodos: 249.3 Fix: invalidateQueries
- useQueryClient() gives the query client.
- onSuccess runs after the request succeeds and calls qc.invalidateQueries({ queryKey: ["todos"] }).
- Invalidate = mark as stale; if the query is active on screen it refetches immediately.
- Click Add: Saving..., then Todos: 3.
React (JSX)
function AddTodo() { const qc = useQueryClient(); const { mutate, isPending } = useMutation({ mutationFn: postTodo, onSuccess: () => qc.invalidateQueries({ queryKey: ["todos"], }), }); return ( <button disabled={isPending} onClick={() => mutate("Milk")}> {isPending ? "Saving..." : "Add"} </button> );}Output
-- initial --[button] AddTodos: 2 -- request running --[button] Saving...Todos: 2 -- after invalidate + refetch --[button] AddTodos: 3- Step 1
1.mutate("Milk"): POST request to the server
- Step 2
2.Server succeeds: onSuccess runs
- Step 3
3.invalidateQueries marks ["todos"] stale
- Step 4
4.Active query refetches
- Step 5
5.Screen shows Todos: 3
49.4 Checkpoint: prefix matching
- Cache has ["todos"], ["todos", 7] and ["user"]; we invalidate ["todos"].
- Answer: the first two. Query keys match by prefix; ["user"] is untouched.
- Pass exact: true to invalidate only the exact key.
JavaScript
const qc = new QueryClient();qc.setQueryData(["todos"], []);qc.setQueryData(["todos", 7], {});qc.setQueryData(["user"], {}); await qc.invalidateQueries({ queryKey: ["todos"],}); for (const q of qc.getQueryCache().getAll()) { console.log(q.queryKey, q.state.isInvalidated);}Output
> [ 'todos' ] true> [ 'todos', 7 ] true> [ 'user' ] false49.5 Optimistic update
- For likes or adding a todo, waiting for the server feels slow: assume success and update the cache first.
- onMutate: cancelQueries so an old in-flight response does not overwrite our change.
- Snapshot with getQueryData (previous), then setQueryData adds the new todo; return { previous } as context.
- onError: put ctx.previous back (rollback), so Milk disappears.
- onSettled (success or error): invalidate so cache and server match in the end.
JavaScript
const key = ["todos"];const addTodo = useMutation({ mutationFn: postTodo, onMutate: async (todo) => { await qc.cancelQueries({ queryKey: key }); const previous = qc.getQueryData(key); qc.setQueryData(key, (old) => [...old, todo]); return { previous }; }, onError: (err, todo, ctx) => qc.setQueryData(key, ctx.previous), onSettled: () => qc.invalidateQueries({ queryKey: key }),});Output
-- before click --Bread[button] Add -- right after click (before server reply) --BreadMilk[button] AddOutput
-- optimistic --BreadMilk[button] Add -- server failed: rolled back --Bread[button] Add- Step 1
1.mutate(todo) calls onMutate
- Step 2
2.cancelQueries + snapshot previous list
- Step 3
3.setQueryData: Milk shows immediately
- Step 4
4.Server fails? onError restores previous
- Step 5
5.onSettled: invalidateQueries syncs with the server
Three must-have steps: cancel, snapshot, roll back
49.6 useInfiniteQuery: Load more
- For feeds where Load more fetches the next page (like an Instagram feed).
- queryFn receives pageParam; initialPageParam is required in v5.
- getNextPageParam returns the next page number from the last page; undefined means no more pages.
- data.pages is an array of pages: flatMap them into one list.
- fetchNextPage() loads the next page; disable the button when hasNextPage is false.
JavaScript
import { useInfiniteQuery } from "@tanstack/react-query"; export function usePosts() { return useInfiniteQuery({ queryKey: ["posts"], queryFn: ({ pageParam }) => getPosts(pageParam), initialPageParam: 1, getNextPageParam: (last) => last.nextPage, });}React (JSX)
export function Feed() { const feed = usePosts(); const pages = feed.data?.pages ?? []; const list = pages.flatMap((p) => p.posts); return ( <> <PostList posts={list} /> <button disabled={!feed.hasNextPage} onClick={() => feed.fetchNextPage()}> Load more </button> </> );}Output
-- first page --Post 1Post 2[button] Load more -- after Load more (no next page) --Post 1Post 2Post 3Post 4[button] Load more (disabled)49.7 Comparison: useQuery vs useMutation vs useInfiniteQuery
| Point | useQuery | useMutation | useInfiniteQuery |
|---|---|---|---|
| Purpose | Read + cache | Create / update / delete | Read data in pages |
| Runs | Automatically on mount / key change | Only when mutate() is called | Automatically, then fetchNextPage() |
| Key result | data, isPending, isFetching | mutate, isPending | data.pages, hasNextPage, fetchNextPage |
| After | Refetches when stale | Invalidate related queries | getNextPageParam decides the next page |
49.8 Common mistakes
- Mutating the cache in setQueryData (old.push(todo); return old): same reference, no re-render, old screen.
- Fix: always return a new array: [...old, todo].
- Forgetting to invalidate after a mutation.
- Myth: add an optimistic update to every mutation. Use it only when success is very likely (like, toggle); for payment or placing an order use plain invalidation so the UI updates only after confirmation.
JavaScript
qc.setQueryData(["todos"], (old) => { old.push(todo); return old;});JavaScript
qc.setQueryData(["todos"], (old) => [ ...old, todo,]);49.9 Rules for mutations
- Invalidate related queries after a change; keep keys hierarchical (["todos"], ["todos", id]).
- Never skip the optimistic steps: cancel, snapshot, roll back.
- Infinite queries need initialPageParam; return undefined from getNextPageParam at the end.
49.10 Interview tips
- useQuery reads and caches, runs automatically; useMutation changes data and runs only on mutate.
- After a successful mutation, invalidate the related queries (keys match by prefix).
- Optimistic update: onMutate updates the cache, onError rolls back, onSettled refetches.
- useInfiniteQuery: pages + getNextPageParam + fetchNextPage.