๐ฎ Optimistic Response in Apollo Client
A short walkthrough of Apollo Client's optimisticResponse, the small option that makes mutations feel instant by updating the UI before the server replies.
The gap between a user clicking a button and the server confirming what happened is small, but it's the difference between an app that feels alive and one that feels sluggish. Optimistic UI is how you close that gap: you update the screen right away, assuming the mutation will succeed, and quietly reconcile if it doesn't.
Apollo Client gives you a tidy way to do this through the optimisticResponse option on useMutation. You hand it the shape the server is about to return, and Apollo writes that into the cache immediately so every component reading the same data re-renders with the new state. When the real response arrives, Apollo swaps the optimistic value out. If the mutation fails, the cache rolls back on its own.
๐ Example
Take the most tired example in the book: a todo with a completed flag. Toggling it is a fine place to use this pattern, because the UI change is obvious and the user expects the checkbox to move the instant they tap it.
type Todo { id: ID! title: String! completed: Boolean! }
The trick is to describe exactly what the server is going to say, including the __typename fields, so Apollo can normalize it into the cache the same way it normalizes a real response.
const [updateTodo] = useMutation(UPDATE_TODO, { optimisticResponse: { __typename: 'Mutation', updateTodo: { __typename: 'Todo', id: todo.id, completed: !todo.completed, }, } });
From there, calling the mutation looks like any other. Apollo handles the optimistic write and the eventual swap for you, so your handler stays boring, which is exactly what you want.
const handleToggle = () => { updateTodo({ variables: { id: todo.id, completed: !todo.completed, }, }); };
That's the whole idea. A few lines of configuration, and your interface stops waiting on the network for feedback it already knows how to predict.