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

Optimistic UI with Apollo

Implementing optimistic responses to show instant UI updates before the server confirms the mutation.

Optimistic UI with Apollo

What you'll learn: How to make your Apollo-powered app feel instant by updating the UI before the server confirms your mutation succeeded.

What Is Optimistic UI?

Optimistic UI means assuming your mutation will succeed and updating the interface immediately, before waiting for the server response. If the mutation fails, Apollo rolls back the change automatically.

Think of it like hitting "send" on a text message — the app shows it as sent instantly, even though it's still traveling through the network. If it fails, only then do you see an error.

Implementing Optimistic Responses

When calling useMutation, pass an optimisticResponse option. This tells Apollo what the data should look like if everything goes well:

const [addTodo] = useMutation(ADD_TODO, {
  optimisticResponse: {
    addTodo: {
      __typename: 'Todo',
      id: 'temp-id-' + Date.now(),
      text: 'New todo',
      completed: false
    }
  }
});

Apollo immediately writes this optimistic data to the cache, triggering a re-render. Your UI updates instantly. When the real response arrives, Apollo replaces the temporary data with the actual result from the server.

Why It Matters

Optimistic UI transforms how responsive your app feels. Instead of spinners and waiting, users see their actions take effect immediately. Combined with cache updates (from the previous lesson), this creates a seamless experience where mutations feel local-first, even though they're backed by a server.

The best part? Apollo handles the rollback complexity — if the mutation fails, it restores the previous cache state automatically.

Key Takeaway: Optimistic responses let you update Apollo's cache immediately with predicted data, making mutations feel instant while Apollo handles rollbacks if things go wrong.