Mutations and optimistic UI on the client

Intermediate · 4 min

Run mutations with Apollo Client, keep the cache current with refetchQueries or update, and show results early with optimisticResponse.

Before thisThe Apollo cacheMutationsDesigning mutation inputs and payloads

Eric Tech · 4 min

Mutations and optimistic UI on the client

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Eric TechReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • useMutation returns a function you call on demand, plus loading and error state; unlike a query it does not run on mount.
  • A mutation that returns an entity with its id updates that entity in the cache automatically.
  • Adding or removing items in a list is not automatic, so use refetchQueries for simplicity or an update function for no extra request.
  • optimisticResponse writes a guess into a separate optimistic layer, which is discarded and replaced when the real response arrives.

A write that has to reach the screen

A query is a read the cache can answer. A mutation changes something on the server, and the cache knows nothing about it. After addBook, the books list you fetched five minutes ago is stale. The job of this lesson is closing that gap, and then making it feel instant.

Running a mutation

In React you use useMutation, which does not fire on mount. It hands back a function:

import { useMutation } from "@apollo/client/react";

const ADD_BOOK = gql`
  mutation Add($title: String!, $authorId: ID!) {
    addBook(title: $title, authorId: $authorId) {
      id title author { id name }
    }
  }
`;

const [addBook, { loading, error }] = useMutation(ADD_BOOK);
// onClick: addBook({ variables: { title: "Parable", authorId: "2" } })

The component code above is docs-derived. I ran the same operations with client.mutate in Node against a local Yoga server and @apollo/client 4.3.8, which exercises the same cache behaviour.

Note the selection set. The mutation returns id and the fields the UI shows. That follows the payload advice from designing mutation inputs and payloads: return the changed object so the client can use it.

What the cache does for free

If a mutation returns an entity the cache already knows, with its __typename and id, the cache merges the new fields into that entity. Renaming a book needs no extra code; every query that points at Book:1 re-renders. This is the normalisation from the previous lesson paying off.

A new entity is different. Writing Book:3 into the cache does not put it into the books list stored under ROOT_QUERY, because nothing says it belongs there. You have two options.

refetchQueries reruns named queries after the mutation: useMutation(ADD_BOOK, { refetchQueries: ["Books"] }). One line, always correct, one extra request. It is the right default.

An update function edits the cache directly and avoids the request:

update(cache, { data }) {
  cache.modify({
    fields: {
      books(existing = []) {
        const ref = cache.writeFragment({
          data: data.addBook,
          fragment: gql`fragment N on Book { id title author { id name } }`,
        });
        return [...existing, ref];
      },
    },
  });
}

I ran this and the books query read back ids 1, 2, 3 with no refetch. The catch is that you are now responsible for keeping the list consistent, including ordering and any filtered variants of the list that are cached under other arguments.

Optimistic UI

A round trip takes time, and most mutations succeed. Optimistic UI shows the expected result immediately and corrects it if the server disagrees. In Apollo you describe the guess with optimisticResponse, shaped exactly like the real response:

client.mutate({
  mutation: ADD_BOOK,
  variables: { title: "Parable", authorId: "2" },
  optimisticResponse: {
    addBook: { __typename: "Book", id: "tmp", title: "Parable",
      author: { __typename: "Author", id: "2", name: "Octavia" } },
  },
  update, // same update function as above
});

Apollo applies the guess, and your update function, into a separate optimistic layer on top of the real cache. In my run, a watchQuery subscriber saw the list length go from 2 to 3 as soon as the mutation started, then the settled result arrived and the list still had three entries, with the temporary tmp entry replaced by the server’s id. If the mutation fails, Apollo drops the layer and the UI snaps back (documented behaviour; I did not run a failing mutation). That rollback is automatic, so the work you owe is showing the error.

Two cautions. The temporary id must not be mistaken for a real one: do not use it in further requests until the real response lands. And do not make guesses you cannot predict, like server-computed fields. Leave those out and render a placeholder.

What the video covers

Eric Tech’s August 2024 video is under four minutes, and its chapters are: executing a mutation with useMutation, refetching queries and updating local data with refetchQueries(), and updating the cache directly after a mutation with update(). That covers the first two thirds of this lesson. Its chapters do not mention optimisticResponse, so the optimistic section here rests on my own run and Apollo’s documentation, not on the video. The linked Wojciech Matuszewski runner-up covers cache.modify in Apollo Client 3.0, still the same API shape.

Where this fits

This closes the loop from the cache: reads are normalised, writes merge by key, and lists need help. Next, urql and Relay shows how other clients handle the same problems differently.

Check yourself

  1. 01Why did the updated title appear everywhere, but a newly created book did not appear in the list?

    The cache merges the returned entity by key, which fixes existing entries, but it has no way to know the new entity belongs in a list you fetched earlier.

  2. 02What is the trade-off between refetchQueries and an update function?

    refetchQueries is one line but makes an extra request. update makes no request but you write the cache change yourself and must get it right.

  3. 03What happens to an optimistic result if the mutation fails?

    Apollo removes the optimistic layer, so the UI returns to the pre-mutation data, and the error is surfaced for you to display.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark