How do you handle optimistic UI in GraphQL with Apollo?
Answer
Optimistic UI means updating the UI immediately with an expected result before the server confirms the mutation — making the app feel faster and more responsive. In Apollo Client, pass an optimisticResponse option to useMutation: const [addTodo] = useMutation(ADD_TODO, { optimisticResponse: { addTodo: { __typename: 'Todo', id: 'temp-id', text: newText, completed: false } }, update(cache, { data: { addTodo } }) { cache.modify({ fields: { todos(existing) { return [...existing, makeReference(cache.identify(addTodo))]; } } }); } });. Apollo writes the optimistic response to the cache immediately, the UI re-renders, and when the real response arrives, the optimistic entry is replaced. If the mutation fails, the optimistic update is rolled back. Works well for likes, upvotes, adding list items, and other low-risk operations.
Previous
What is the Apollo Cache and how does normalized caching work?
Next
What are Apollo Client hooks and how do you use them?
More GraphQL Questions
View all →- Intermediate How do you implement pagination in GraphQL?
- Intermediate What is the Relay specification in GraphQL?
- Intermediate How do you implement authorization in GraphQL resolvers?
- Intermediate What is graphql-shield and how does it work?
- Intermediate How do you implement real-time subscriptions with GraphQL?