Course contentsShow
← React
Lesson 1797 of 2,39642. Data Fetching LibrariesFree lesson

Rolling Back Failed Optimistic Updates

Restore the previous cache snapshot in onError to revert optimistic changes when mutations fail.

Rolling Back Failed Optimistic Updates

You'll learn how to restore your cache when an optimistic mutation fails, keeping your UI consistent with reality.

When you optimistically update your UI before a mutation completes, you're taking a gamble: you assume the server will succeed. But what happens when the network fails or the server rejects your request? Your UI now shows fake data that never actually saved.

The Rollback Pattern

In your onMutate callback, you snapshot the previous cache state before making optimistic changes. If the mutation fails, your onError callback restores that snapshot, effectively "undoing" the optimistic update.

Think of it like writing in pencil before getting confirmation. If the teacher says "wrong answer," you erase what you wrote and restore your original work.

Implementation

Here's the critical flow:

const mutation = useMutation({
  mutationFn: updateTodo,
  
  onMutate: async (newTodo) => {
    await queryClient.cancelQueries({ queryKey: ['todos'] });
    
    // Snapshot the previous value
    const previousTodos = queryClient.getQueryData(['todos']);
    
    // Optimistically update
    queryClient.setQueryData(['todos'], (old) => [...old, newTodo]);
    
    // Return the snapshot in context
    return { previousTodos };
  },
  
  onError: (err, newTodo, context) => {
    // Restore the snapshot on failure
    queryClient.setQueryData(['todos'], context.previousTodos);
  },
});

The context object passed to onError contains whatever you returned from onMutate — your safety net. By restoring context.previousTodos, you revert the cache to its pre-optimistic state, making the failed change disappear instantly.

Why This Matters

Without rollback, failed mutations leave your UI showing data that doesn't exist on the server. Users see "success" when they actually failed. Rolling back maintains truth between client and server.

Key Takeaway: Always return a snapshot from onMutate and restore it in onError to gracefully undo optimistic updates when mutations fail.