Optimistic updates with React Query mutations

8799
0

Optimistic updates make UIs feel instant by immediately showing the expected result before the server confirms. When a user likes a post, I update the local cache immediately, submit the request in background, and rollback if it fails. React Query's mutation callbacks (onMutate, onError, onSettled) orchestrate this flow. The onMutate function snapshots the current cache, updates it optimistically, and returns the snapshot for potential rollback. If the mutation fails, onError restores the snapshot. The onSettled callback runs regardless of success/failure to ensure cache consistency. This pattern dramatically improves perceived performance for actions like likes, follows, or simple edits where failures are rare.