Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 38 ยท Optimistic Updates

Optimistic Updates: Edge Cases

Handle the hard parts of optimistic updates in TanStack Query: overlapping mutations, isMutating guards, temporary IDs, infinite list edits and serial mutation scopes.

The basic optimistic recipe works perfectly for one click on a fast connection. Real users double-click, toggle three items in a row, add an item and immediately edit it, and go through tunnels. This lesson covers the situations that break naive code and the small additions that fix each one.

Problem 1: overlapping mutations

Click item A, then item B before A's request finishes. Both mutations run onSettled and both call invalidateQueries. The first settled mutation triggers a refetch while the second request is still in flight, so the refetched list may not yet contain B's change, and it overwrites B's optimistic update. B flickers back, then forward again when its own refetch arrives.

The fix is to refetch only when the last mutation settles. queryClient.isMutating counts mutations in flight for a key:

JavaScript
onSettled: () => {
  if (queryClient.isMutating({ mutationKey: ["todos"] }) === 1) {
    queryClient.invalidateQueries({ queryKey: ["todos"] });
  }
},

It is === 1 because the mutation that is calling onSettled still counts as in flight while its callbacks run. This requires a mutationKey: ["todos"] on useMutation.

JS Counting in-flight mutations

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

No output.

Three mutations, one refetch, at the very end. Without the guard you would have refetched three times, and the first two refetches could have undone optimistic state.

Problem 2: temporary ids for new items

When creating an item optimistically you do not know the server id. Give it a temporary one and mark it:

JavaScript
onMutate: async (newTodo) => {
  await queryClient.cancelQueries({ queryKey: ["todos"] });
  const previous = queryClient.getQueryData(["todos"]);
  const temp = { id: "temp-" + crypto.randomUUID(), ...newTodo, pending: true };
  queryClient.setQueryData(["todos"], (old = []) => [...old, temp]);
  return { previous, tempId: temp.id };
},
onSuccess: (saved, vars, ctx) => {
  queryClient.setQueryData(["todos"], (old = []) =>
    old.map((t) => (t.id === ctx.tempId ? saved : t)));
},

Rules for temporary items:

  • Render them differently (faded) using the pending flag.
  • Disable actions that need a real id (edit, delete) until the id is replaced, or the request would hit a URL like /todos/temp-8f3a.
  • Use the temp id as the React key and keep it until the swap, so React does not remount the row when the real id arrives. A common trick is to keep a stable clientId field next to id.

Problem 3: edits to an infinite list

An item inside an infinite query lives at data.pages[i].items[j]. Update it with setQueryData while preserving the shape:

JavaScript
const patchItem = (id, patch) => (old) =>
  old && {
    ...old,
    pages: old.pages.map((page) => ({
      ...page,
      items: page.items.map((it) => (it.id === id ? { ...it, ...patch } : it)),
    })),
  };

queryClient.setQueryData(["feed"], patchItem(7, { liked: true }));

Deleting is the same with filter. Adding is harder because you must choose which page receives the item; most apps prepend to the first page:

JavaScript
queryClient.setQueryData(["feed"], (old) => old && ({
  ...old,
  pages: old.pages.map((p, i) => (i === 0 ? { ...p, items: [newItem, ...p.items] } : p)),
}))
JS Patching an item inside pages

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

No output.

Only the changed item gets a new object, and pageParams survives. Page 0 was rebuilt by map, yet the last line prints true: structural sharing compares the new data with the old and reuses every part that is deeply equal, so unchanged pages and rows keep their identity and their components do not re-render.

Problem 4: ordering of mutations on one resource

Two quick edits of the same todo (rename, then toggle) may reach the server out of order, and the later change could be lost. Give mutations a scope. Mutations with the same scope.id run one after another instead of in parallel:

JavaScript
useMutation({
  mutationFn: updateTodo,
  scope: { id: "todo-" + todo.id },
})

Mutations in different scopes still run in parallel. Use a scope per resource that must be edited in order.

Problem 5: going offline

With the default networkMode: "online", a mutation started while offline pauses (isPaused is true) and resumes when the connection returns, without losing the optimistic UI. Retry settings apply on top: a failed request is retried with exponential backoff (3 times for queries; mutations default to 0 retries). For persistent offline support across reloads you need persistQueryClient plus setMutationDefaults, because the mutationFn function cannot be serialized and must be registered by key.

Problem 6: should this be optimistic at all?

Not every update should be optimistic. Avoid it when:

  • The server often rejects the change (payments, usernames, stock reservations): users who see success and then an error feel tricked.
  • The result depends on server computation (totals, ranks, generated text) you cannot predict.
  • An undo is destructive (a visible delete that the server later refuses must come back and re-order everything).

For those, show a pending state and update when the server confirms. Optimistic UI is a tradeoff: speed in the common case against honesty in the failure case.

A short checklist

  1. mutationKey set on every mutation that edits a given list.
  2. cancelQueries first in onMutate.
  3. Snapshot returned as context; rollback in onError.
  4. Refetch in onSettled only when isMutating(...) === 1.
  5. Temp ids disable id-dependent actions.
  6. Scopes on resources that need ordered writes.
  7. Tests for the failure path.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why compare isMutating(...) with 1 inside onSettled?

    When onSettled runs, the finishing mutation is still in flight. A count of 1 means no other mutation is pending, so it is safe to refetch.
  2. 2. What should you do with action buttons for an item that has a temporary id?

    Requests for a temporary id would hit a resource that does not exist on the server.
  3. 3. What does scope: { id } do on a mutation?

    Mutations sharing a scope id run one after another, which keeps writes to one resource in order.
  4. 4. In an infinite query, where does an item live?

    Pages are an array of your page results, so an optimistic edit maps over pages and then items, preserving pageParams.

Summary

  • Refetch only after the last overlapping mutation, using mutationKey and isMutating.
  • Temporary ids need a pending marker and disabled id-dependent actions.
  • Edit infinite data by mapping over pages and keeping pageParams.
  • scope.id serializes writes to one resource.
  • Skip optimistic updates when the server often refuses or computes the result.

Next: Suspense Queries