Skip to main content
Optimistic updates provide instant feedback to users by updating the UI before the server confirms the change. This creates a more responsive experience, especially for actions that are likely to succeed.

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
Optimistic updates assume success. Always implement proper rollback logic for when mutations fail.

UI-Based Optimistic Updates

The simplest approach: show the pending state in the UI using mutation state.
UI-based optimistic updates are simpler to implement and don’t require rollback logic since they don’t modify the cache.

Cache-Based Optimistic Updates

For more complex scenarios, update the cache directly using the onMutate 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

Handle Edge Cases

Provide Visual Feedback

Always Use onSettled

Never skip the onSettled callback when using cache-based optimistic updates. It’s your safety net for ensuring cache consistency.