Why Optimistic Updates?
Optimistic updates improve perceived performance by:- Providing instant visual feedback
- Reducing perceived latency
- Making the app feel more responsive
- Improving user experience for common actions
UI-Based Optimistic Updates
The simplest approach: show the pending state in the UI using mutation state.Cache-Based Optimistic Updates
For more complex scenarios, update the cache directly using theonMutate callback:
1
Cancel outgoing queries
Cancel any in-flight refetches so they don’t overwrite your optimistic update.
2
Snapshot previous state
Save the current cache state for rollback if the mutation fails.
3
Update the cache
Optimistically update the cache with the expected result.
4
Return context
Return an object containing the snapshot for use in error/success callbacks.
5
Handle errors
Roll back to the previous state if the mutation fails.
6
Refetch on settle
Always invalidate to ensure cache consistency with the server.
Update Operations
Optimistically update existing items:Delete Operations
Optimistically remove items:Multiple Query Updates
Update multiple related queries optimistically:Using Response Data
Update the cache with the server response:When using optimistic updates, you don’t always need to invalidate in
onSuccess if you update the cache with the server response.Best Practices
Choose the Right Strategy
- UI-based: Simple additions, low risk of conflicts
- Cache-based: Complex updates, multiple related queries