Sub topic 11
Optimistic updates with rollback
This chapter assumes you know useMutation, query keys, and invalidation from the earlier chapters. You should also be comfortable with TypeScript and async/await.
What an optimistic update is
A normal mutation waits for the server before the UI changes. On a slow network, a checkbox click can feel broken. An optimistic update writes the expected result into the cache right away, then fixes the cache if the server disagrees.
The pattern has four steps:
- Cancel any in-flight fetches for the affected key, so an older response cannot overwrite your change.
- Save a snapshot of the current cache data.
- Write the expected result into the cache.
- On error, restore the snapshot. When the mutation finishes either way, refetch to match the server.
The code
This hook toggles a todo's done flag.
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'] })
},
})
}How each callback works
onMutateruns before the request starts. Whatever it returns becomes thecontextpassed to later callbacks. Here it returns the snapshot.cancelQueriesstops running fetches for['todos']. Without it, a slow refetch that started before your click could finish afterward and bring back the old value.setQueryDatatakes an updater function. Always return a new array or object, and never mutateoldin place, or React may not re-render.onErrorreceives the error, the variables, and the context. It writes the snapshot back.onSettledruns after success and after failure. Refetching here means the cache ends up matching the server, even if your guess about the result was slightly wrong.
Common errors
- Forgetting to cancel queries. The optimistic value flickers back to the old one.
- Skipping the snapshot. Without
previous,onErrorhas nothing to restore. - Mutating cached data. Use spread syntax or
map, not assignment. - Wrong key. If the list is cached under
['todos', { filter }], updating['todos']changes a different cache entry. Match the exact key you display. - Using it for risky changes. If failures are common or hard to undo, such as payments, wait for the server instead.
Exercise
A user toggles a todo, but the server returns a 500 error. Which callbacks run, and what is the final state of the cache?
Show answer
onMutate runs first and updates the cache. When the request fails, onError restores the saved snapshot, then onSettled invalidates ['todos'] and triggers a refetch. The cache ends up matching the server's data, which is the original, unchanged todo.