GraphQL Mutations and Optimistic UI Updates
GraphQL Mutations and Optimistic UI Updates
While queries read data, Mutations modify server-side resources. In high-performance enterprise applications, waiting 500ms for a network roundtrip before updating a "Like", "Checkmark", or "Status" button creates perceived lag. Optimistic UI updates immediately render expected mutations in the UI before server confirmation, rolling back cleanly if the request fails.
1. Anatomy of useMutation
mutateFunction(options): Dispatches the mutation request.refetchQueries: Specifies queries to refetch after mutation succeeds.update(cache, { data }): Directly updates the normalized cache without triggering extra network requests.optimisticResponse: Provides temporary synthetic data written to the cache immediately upon dispatch.
2. Implementing Optimistic Updates
Consider toggling a task's completed status:
3. How Apollo Handles Failures
If the server rejects the mutation (e.g. 500 Internal Server Error or permission denied):
- 1Apollo Client detects the network error.
- 2It automatically rolls back the optimistic snapshot from the cache.
- 3The UI instantaneously returns to its previous valid state without manual recovery code!
4. Cache Eviction on Deletion
When deleting records, use cache.evict to purge the deleted entity from memory:
Practice Quiz
Real-Time GraphQL Subscriptions with WebSockets
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Executing GraphQL Queries with useQuery | Real-Time GraphQL Subscriptions with WebSockets |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.