Cache Updates After Mutations
You'll learn how to manually synchronize Apollo Client's cache with server changes after mutations without needing extra queries.
The Problem with Stale Cache
When you execute a mutation (like adding a new item or deleting one), the server's data changes—but Apollo Client's local cache doesn't automatically know about these changes. Your UI might display outdated data unless you refetch queries or update the cache yourself.
Think of it like a librarian (Apollo) keeping an index card catalog (cache). When someone returns a book (mutation happens), the librarian needs explicit instructions to update their cards—otherwise they'll still show the book as checked out.
Manual Cache Updates with update
The useMutation hook accepts an update function that runs after a successful mutation. Inside, you receive the cache object and can read from it, modify it, and write changes back:
const [addTodo] = useMutation(ADD_TODO, {
update(cache, { data: { addTodo } }) {
// Read existing todos from cache
const existing = cache.readQuery({ query: GET_TODOS });
// Write updated list back
cache.writeQuery({
query: GET_TODOS,
data: {
todos: [...existing.todos, addTodo]
}
});
}
});
This pattern ensures your UI reflects the new todo immediately without refetching the entire list from the server.
When to Use It
Use manual cache updates when:
- Adding items to lists
- Removing items from arrays
- Updating fields that appear in multiple queries
- You want instant UI feedback without network delay
Key Takeaway: The update function in mutations gives you surgical control over Apollo's cache, letting you synchronize local state with server changes for responsive, efficient UIs.