Course contentsShow
← React
Lesson 1498 of 2,39637. React 19 and BeyondFree lesson

The Optimistic State Pattern

Master the optimistic update flow: show immediate change, send request, roll back on error, or confirm on success.

The Optimistic State Pattern

What you'll learn: How to structure optimistic updates so users see instant feedback, then either confirm success or gracefully roll back on errors.

The Three-Phase Flow

The optimistic state pattern is a structured approach to making your UI feel instant without lying to users. It works in three phases:

  1. Show the optimistic change immediately — Update the UI as if the server request already succeeded
  2. Send the actual request — Make the network call in the background
  3. Resolve the outcome — Either confirm the optimistic state (on success) or roll it back (on error)

Think of it like paying with a credit card at a gas pump. The pump lets you fill up immediately (optimistic), processes payment in the background (request), then either completes successfully or declines and asks you to pay inside (rollback).

The Pattern in Practice

When a user likes a post, you don't wait for the server:

// Phase 1: Optimistic update
const optimisticLikes = currentLikes + 1;
setOptimisticState(optimisticLikes);

// Phase 2: Send request
const result = await likePost(postId);

// Phase 3: Resolve
if (result.success) {
  // Confirm: optimistic state becomes real state
  setActualLikes(result.likes);
} else {
  // Rollback: revert to original state
  setOptimisticState(currentLikes);
  showError(result.error);
}

The key is tracking both the "optimistic" version (what we hope happens) and the "actual" version (truth from the server), then reconciling them.

Why It Matters

This pattern prevents common mistakes: forgetting to handle errors, leaving stale optimistic data after failures, or showing confusing mixed states. It's a discipline that makes your UX feel fast while staying honest about what's actually saved.

Key Takeaway: The optimistic state pattern structures updates as immediate → request → confirm-or-rollback, giving users instant feedback while gracefully handling failures.