Implementing Optimistic Updates with onMutate
You'll learn how to use the onMutate callback to snapshot current cache data and apply optimistic changes before the server responds.
The onMutate Callback
In the previous lesson, you learned the pattern of optimistic updates. Now let's implement it using TanStack Query's onMutate callback. This function runs before the mutation request is sent, giving you a chance to modify the cache immediately.
The onMutate callback receives the mutation variables (the data you're sending) and should return a "context" object. This context gets passed to your onError and onSettled callbacks, allowing you to roll back changes if something goes wrong.
The Two-Step Process
Step 1: Snapshot the current state Before making optimistic changes, save the current cache data. If the mutation fails, you'll need this to restore the original state.
Step 2: Apply the optimistic update
Use queryClient.setQueryData() to immediately update the cache with your predicted outcome.
Think of it like writing in pencil before the teacher confirms your answer. You write confidently, but keep an eraser (the snapshot) ready just in case.
Example Structure
const mutation = useMutation({
mutationFn: updateTodo,
onMutate: async (newTodo) => {
// Cancel outgoing refetches
await queryClient.cancelQueries({ queryKey: ['todos'] });
// Snapshot current cache
const previousTodos = queryClient.getQueryData(['todos']);
// Optimistically update cache
queryClient.setQueryData(['todos'], (old) => [...old, newTodo]);
// Return context with snapshot
return { previousTodos };
}
});
The cancelQueries call prevents race conditions where an automatic refetch might overwrite your optimistic update.
Key Takeaway: The onMutate callback lets you snapshot existing cache data and apply optimistic updates synchronously, with the returned context enabling safe rollbacks on error.