Course contentsShow
← React
Lesson 1826 of 2,39642. Data Fetching LibrariesFree lesson

Cache Updates After Mutations

Manually updating Apollo's cache after mutations using update functions, readQuery, and writeQuery.

Cache Updates After Mutations

What you'll learn: How to manually update Apollo Client's cache after mutations so your UI instantly reflects changes without refetching queries.

Why Manual Cache Updates Matter

After a mutation (like adding a todo), Apollo Client doesn't automatically know which queries now have stale data. You could refetch queries, but that's slow and wasteful. Instead, you can manually update the cache directly, making your UI feel instant.

The update Function

Every useMutation accepts an update callback that receives two arguments:

  • cache: Apollo's cache interface
  • result: The mutation's response data

Inside update, you read the current cached query data, modify it, then write it back.

Reading and Writing Cache Data

Use cache.readQuery to retrieve existing query data:

const cachedData = cache.readQuery({
  query: GET_TODOS_QUERY
});

Then use cache.writeQuery to update it:

cache.writeQuery({
  query: GET_TODOS_QUERY,
  data: {
    todos: [...cachedData.todos, newTodo]
  }
});

Complete Example

const [addTodo] = useMutation(ADD_TODO_MUTATION, {
  update(cache, { data: { addTodo } }) {
    const existing = cache.readQuery({ query: GET_TODOS_QUERY });
    
    cache.writeQuery({
      query: GET_TODOS_QUERY,
      data: {
        todos: [...existing.todos, addTodo]
      }
    });
  }
});

Now when you add a todo, the list updates immediately without waiting for the server or triggering a refetch.

The Analogy

Think of Apollo's cache like a filing cabinet. After filing a new document (mutation), you manually update the index card (cache) so everyone sees the new document immediately—no need to recount every file.

Key Takeaway: Use update with readQuery and writeQuery to manually synchronize Apollo's cache after mutations, eliminating unnecessary refetches and creating instant UI updates.