Sub topic 11
Optimistic updates with rollback
An optimistic update changes the UI as if a mutation had already succeeded, before the server replies. If the server later rejects the change, the UI goes back to its previous state. This chapter shows how to build that flow with TanStack Query v5 and where it tends to break.
This chapter assumes you know useQuery, query keys, useMutation, and invalidation. It also assumes basic TypeScript and async/await.
Why update before the server answers
A normal mutation has a visible delay. The user clicks a checkbox, the request travels to the server, the response returns, the cache is invalidated, a refetch runs, and only then does the checkbox change. On a slow network that takes seconds. The interface feels broken even though nothing is wrong.
An optimistic update removes the wait by betting that the request will succeed. Most requests do. The bet has a cost: you must handle the case where it loses, and you must make sure the final UI matches the server.
Use it for small, high-confidence actions such as toggling a checkbox, liking an item, or reordering a list. Avoid it when the server often rejects the change, or when the result depends on server-side data you cannot predict, such as a generated id or a computed total.
The four-step pattern
The pattern uses the mutation lifecycle callbacks. Each callback has a specific job.
onMutateruns before the request is sent. Cancel in-flight fetches, save a snapshot of the cache, write the expected result, and return the snapshot.mutationFnsends the request.onErrorruns if the request fails. It receives the value returned byonMutateas its third argument, called the context. Use it to restore the snapshot.onSettledruns after success or failure. Invalidate the query so the cache is replaced by what the server actually holds.
The full example
This hook toggles the done flag on a todo. It assumes the list is cached under ['todos'].
import { useMutation, useQueryClient } from '@tanstack/react-query'
type Todo = { id: number; title: string; done: boolean }
function useToggleTodo() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: async (todo: Todo) => {
const res = await fetch(`/api/todos/${todo.id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ done: !todo.done }),
})
if (!res.ok) throw new Error(`Request failed: ${res.status}`)
return res.json()
},
onMutate: async (todo) => {
await queryClient.cancelQueries({ queryKey: ['todos'] })
const previous = queryClient.getQueryData<Todo[]>(['todos'])
queryClient.setQueryData<Todo[]>(['todos'], (old) =>
old?.map((t) => (t.id === todo.id ? { ...t, done: !t.done } : t)),
)
return { previous }
},
onError: (_error, _todo, context) => {
queryClient.setQueryData(['todos'], context?.previous)
},
onSettled: () => {
queryClient.invalidateQueries({ queryKey: ['todos'] })
},
})
}Why each line is there
cancelQueries stops any refetch already running for ['todos']. Without it, a slow response that was requested before the mutation can arrive afterward and overwrite your optimistic value. The user would see the checkbox flip back and then flip forward again.
getQueryData reads the cache synchronously and returns undefined if nothing is cached. The snapshot is the exact value to restore, so keep a reference to it and do not modify it.
setQueryData receives an updater function. The updater must return a new array and new objects, which is why the code uses map and spreads the todo. Mutating old in place can leave components without a re-render, because the reference does not change. The old?. guard handles the case where the cache is empty.
Returning { previous } from onMutate is what delivers the snapshot to onError as context.
onSettled runs on both outcomes. After a success, it replaces your guess with the server's real data, which may differ in fields you did not predict, such as an updatedAt timestamp. After a failure, it confirms that the restored data matches the server.
Using the hook
function TodoRow({ todo }: { todo: Todo }) {
const toggle = useToggleTodo()
return (
<label>
<input
type="checkbox"
checked={todo.done}
onChange={() => toggle.mutate(todo)}
/>
{todo.title}
{toggle.isError && <span> Could not save. Change reverted.</span>}
</label>
)
}The checkbox reads todo.done from the cached list, so the optimistic write changes it right away. When the request fails, onError restores the snapshot and the checkbox goes back. The toggle.isError flag lets you tell the user why.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| The UI flickers back to the old value, then forward again | An older fetch finished after the optimistic write | Call `await queryClient.cancelQueries` at the start of `onMutate` |
| Rollback restores the wrong data | Two mutations ran at once and the second snapshot already contained the first optimistic change | Serialize related mutations, or restore by invalidating instead of using a snapshot |
| The UI does not change after `setQueryData` | The updater mutated the old value in place | Return new arrays and objects |
| The list becomes `undefined` after an error | `context` was missing because `onMutate` threw or returned nothing | Return the snapshot from `onMutate` and guard `context?.previous` |
| Cache shows stale fields after success | No `onSettled` invalidation | Invalidate in `onSettled`, not only in `onSuccess` |
Overlapping mutations
The snapshot approach has a real weakness. Suppose the user toggles todo 1, then toggles todo 2 before the first request ends. The second onMutate snapshots a cache that already includes the todo 1 change. If todo 1 fails, its rollback restores the cache from before todo 1, which also erases the optimistic change for todo 2. Then todo 2 succeeds and the final invalidation fixes the list, but the user briefly sees a wrong state.
Two options reduce this. You can invalidate in onError as well, which the example already does through onSettled, so the cache converges to the server state. Or you can avoid snapshots for lists with frequent edits and rely on invalidation alone.
Alternative: optimistic UI from mutation variables
You do not always need to touch the cache. The mutation object exposes variables while it is pending, so a component can render the expected result directly from it.
import { useMutation, useQueryClient } from '@tanstack/react-query'
function AddTodoOptimistic() {
const queryClient = useQueryClient()
const addTodo = useMutation({
mutationFn: async (title: string) => {
const res = await fetch('/api/todos', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title }),
})
if (!res.ok) throw new Error(`Request failed: ${res.status}`)
return res.json()
},
onSettled: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
})
return (
<div>
{addTodo.isPending && <p style={{ opacity: 0.5 }}>{addTodo.variables}</p>}
{addTodo.isError && (
<p>
Failed: {addTodo.variables}{' '}
<button onClick={() => addTodo.mutate(addTodo.variables)}>Retry</button>
</p>
)}
<button onClick={() => addTodo.mutate('Write tutorial')}>Add todo</button>
</div>
)
}This approach has no rollback step because the cache was never changed. It works well for adding items, where the server creates the id, and it lets you show a retry button. Its limit is scope: only the component that owns the mutation sees the pending item.
| Approach | Where the change shows | Rollback | Best for |
|---|---|---|---|
| Cache update with `onMutate` | Every component reading the query | Manual, using a snapshot | Toggles, edits, reorders |
| Render from `variables` | The component that owns the mutation | Not needed | Appending new items |
Checklist
- Cancel related queries before writing to the cache.
- Snapshot with
getQueryDataand return the snapshot fromonMutate. - Write immutable updates with
setQueryData. - Restore the snapshot in
onError. - Invalidate in
onSettled, so success and failure both end with server data. - Show the user an error message when a rollback happens.
Exercise
In the toggle example, you remove await queryClient.cancelQueries({ queryKey: ['todos'] }) from onMutate. A background refetch of ['todos'] was started 200 ms before the user clicks, and the server answers it 300 ms after the click. What does the user see, and why?
Show answer
The checkbox flips immediately because of the optimistic write. When the older refetch response arrives, it replaces the cache with data from before the toggle, so the checkbox flips back. Once the mutation finishes and onSettled invalidates the query, a new refetch returns the toggled value and the checkbox flips forward again. Calling cancelQueries prevents the stale response from being written into the cache.
Exercise
Why does onSettled invalidate the query even when the mutation succeeded and the optimistic value was correct?
Show answer
The optimistic value is a prediction. The server may return additional or different fields, such as a new updatedAt, or another client may have changed the list. Invalidation refetches the data so the cache matches the server rather than the guess.