Course contentsShow
← Web Development
Lesson 1542 of 2,98228. GraphQL FundamentalsFree lesson

Optimistic UI Updates with Mutations

Implement optimistic updates in the UI before the mutation completes for better perceived performance.

Optimistic UI Updates with Mutations

You'll learn how to make your app feel instantly responsive by updating the UI before your GraphQL mutation actually completes on the server.

What Are Optimistic Updates?

When a user clicks "Like" or "Add to Cart," they expect immediate feedback. Waiting for the server to respond creates noticeable lag. Optimistic updates assume the mutation will succeed and update the UI immediately with predicted data, then reconcile when the real server response arrives.

Think of it like ordering coffee: The barista writes your name on a cup right away (optimistic update) even though they haven't made the coffee yet. If something goes wrong, they can always cross it out.

How It Works

With GraphQL mutations, you update your local cache or state before the server responds:

  1. User triggers a mutation (e.g., "Like" button)
  2. Immediately update the UI with the expected result
  3. Send the mutation to the server
  4. When the response arrives, replace the optimistic data with real data
  5. If it fails, roll back the optimistic update
// Optimistic update pattern
const likePost = async (postId) => {
  // Update UI immediately
  updateLocalPost(postId, { liked: true, likes: currentLikes + 1 });
  
  try {
    // Send mutation
    const result = await executeMutation({ postId });
    // Replace with real data
    updateLocalPost(postId, result.data);
  } catch (error) {
    // Roll back on failure
    updateLocalPost(postId, { liked: false, likes: currentLikes });
  }
};

When to Use It

Optimistic updates work best for high-confidence operations like likes, follows, or simple edits where failures are rare. Avoid them for critical operations like payments where you need confirmation first.

Key Takeaway: Optimistic UI updates make your app feel snappy by updating the interface immediately with predicted data, then reconciling with the real server response—dramatically improving perceived performance.