Optimistic Updates: The Pattern
You'll learn how to make your UI feel instant by updating the cache before the server confirms the change, then gracefully handling failures.
The Core Idea
Optimistic updates mean assuming your mutation will succeed and updating the UI immediately, rather than waiting for the server response. If the server returns an error, you rollback to the previous state. This creates a snappy, responsive experience—users see their changes instantly, even on slow networks.
Think of it like ordering coffee: you walk away from the counter with confidence that your order is being made (optimistic), rather than standing there waiting for confirmation. If something goes wrong, they call you back (rollback).
The Pattern
When using useMutation with TanStack Query, optimistic updates follow this flow:
- Before the mutation runs: save the current cache state as a snapshot
- Immediately update the cache: manually modify what users see
- If successful: the server response confirms everything (or you can use it to refine the UI)
- If it fails: restore the snapshot you saved—as if nothing happened
This leverages the onMutate callback (fires before the request), onError (receives your snapshot as context), and onSettled (always runs to clean up).
You're essentially borrowing optimism from your users' trust that things usually work, then apologizing by rolling back if reality disagrees.
Why It Matters
Without optimistic updates, every button click has a delay while the network roundtrip completes. With them, your app feels as fast as native apps—changes appear instantly, and errors are rare enough that the occasional rollback is worth the everyday speed boost.
Key Takeaway: Optimistic updates immediately apply changes to the cache before your mutation resolves, creating an instant UI, then rollback the snapshot if the server reports an error.