Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 38 ยท Optimistic Updates

Optimistic Updates in the Cache

Update the TanStack Query cache before the server answers: cancelQueries, snapshot with getQueryData, setQueryData in onMutate, rollback in onError and refetch in onSettled.

When an optimistic change touches an existing item, or must show up in several components at once, you edit the cache itself. Every component that reads that key re-renders immediately. If the server later rejects the change, you put the old data back.

The recipe has four steps, and each one exists for a reason. Memorize the order: cancel, snapshot, write, then rollback or refetch.

The recipe

JavaScript
const toggle = useMutation({
  mutationFn: toggleTodo,

  onMutate: async (todo) => {
    await queryClient.cancelQueries({ queryKey: ["todos"] });      // 1. stop in-flight fetches
    const previous = queryClient.getQueryData(["todos"]);          // 2. snapshot
    queryClient.setQueryData(["todos"], (old) =>                   // 3. optimistic write
      old.map((t) => (t.id === todo.id ? { ...t, done: !t.done } : t)));
    return { previous };                                           // context for later
  },

  onError: (err, todo, context) => {
    queryClient.setQueryData(["todos"], context.previous);         // 4a. rollback
  },

  onSettled: () => {
    queryClient.invalidateQueries({ queryKey: ["todos"] });        // 4b. truth from the server
  },
})
  1. cancelQueries. A background refetch that started before your click would finish after it and overwrite your optimistic data with the old server state. Cancelling avoids that race.
  2. getQueryData captures the current cache value so you can restore it.
  3. setQueryData with an updater function writes the optimistic value. Never mutate old; return a new array or object, because TanStack Query uses structural sharing and reference equality.
  4. Rollback in onError using the snapshot returned from onMutate, which arrives as the third argument context. onSettled runs after success or failure, and refetching makes the cache match the server whichever happened.
flowchart TD
  A["mutate(todo)"] --> B["onMutate: cancel + snapshot + setQueryData"]
  B --> C["Request to server"]
  C -->|success| D["onSettled: invalidateQueries"]
  C -->|error| E["onError: restore snapshot"]
  E --> D
  D --> F["Cache equals server state"]

Both outcomes end in onSettled, so the cache is always reconciled with the server.

A toggle you can break

The fake server takes one second to answer and fails when you tick the checkbox, so you can watch the optimistic change flip back.

Optimistic toggle with rollback

Tick a todo: the check mark appears immediately, long before the server answers. Now enable "Make the server fail" and tick another one: it checks, then unchecks one second later, and the log shows the rollback.

Why the snapshot comes from onMutate

The value you return from onMutate becomes context for onError and onSettled. Return only what you need to undo the change: the previous list, or for a large list just the previous item. Do not rely on variables captured in a closure: with several mutations in flight, a closure can capture an already-optimistic value.

Updating one item in several caches

A single todo can live in a list query and a detail query. Update both:

JavaScript
queryClient.setQueryData(["todos"], (old) => old?.map((t) => (t.id === id ? { ...t, ...patch } : t)));
queryClient.setQueryData(["todos", id], (old) => (old ? { ...old, ...patch } : old));

Guard against undefined: setQueryData runs your updater even if a query has never loaded, and old will be undefined. Returning undefined from an updater leaves the cache untouched.

To change every list that might contain the item (filtered lists, pages) use setQueriesData, which takes a partial key and updates all matches:

JavaScript
queryClient.setQueriesData({ queryKey: ["todos", "list"] }, (old) =>
  old ? old.map((t) => (t.id === id ? { ...t, ...patch } : t)) : old);

You will use this with infinite and paginated lists, where one item sits inside pages[n].items.

Testing the logic without React

The cache functions are plain methods on QueryClient, so you can check the recipe in isolation. This runs the same four steps without a UI:

JS Rollback logic with QueryClient only

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The last line prints true because the second item's object was never copied: map returned the same reference for it, and structural sharing keeps untouched parts stable so components that only read it do not re-render.

Mistakes that cause bugs

  • Skipping cancelQueries. A slow refetch lands after your write and the UI jumps back to the old state, then forward again.
  • Mutating the cached object. old.push(...) or todo.done = true breaks change detection. Always return new objects.
  • No onSettled refetch. After a successful mutation the optimistic data may differ from what the server computed (ids, timestamps); refetch to reconcile.
  • Rolling back in onSuccess paths. Rollback belongs only in onError.
  • Forgetting that onMutate errors abort the mutation. If your optimistic code throws, the request never runs, and onError receives context as undefined.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why call cancelQueries at the start of onMutate?

    A refetch that began before the mutation would resolve later with old server data and undo the optimistic write.
  2. 2. Where does the snapshot returned from onMutate show up?

    The return value of onMutate is passed as context, the third argument of onError and onSettled's fourth.
  3. 3. Which callback should always run the final invalidateQueries?

    onSettled runs after both success and error, so the cache is always reconciled with the server.
  4. 4. What is wrong with old.push(newItem) in a setQueryData updater?

    Cache data must be treated as immutable. Return a new array, for example [...old, newItem].

Summary

  • Optimistic cache updates follow: cancelQueries, getQueryData, setQueryData, return context.
  • Roll back in onError with the context; reconcile in onSettled with invalidateQueries.
  • Always treat cache data as immutable and guard against undefined.
  • Use setQueriesData to update many cache entries that share a key prefix.
  • Cache edits update every component that reads the key at once.

Next: Optimistic Updates: Edge Cases