⬡ GraphQL Intermediate

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.