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

Handling Optimistic Update Failures

Implement error handling for failed optimistic updates, reverting UI state and showing appropriate error messages.

Handling Optimistic Update Failures

You'll learn how to gracefully recover when optimistic UI updates don't match server reality.

The Problem with Optimism

Optimistic updates make your UI feel instant by updating state before the server confirms the action succeeded. But what happens when the server says "no"? Maybe the network failed, validation rejected the data, or another user already modified the same resource. Without proper error handling, your UI shows incorrect state — the user thinks their action succeeded when it actually failed.

Think of it like writing a check before confirming you have funds: if the bank rejects it, you need to undo that mental accounting and show an error message.

Reverting and Notifying

When an optimistic update fails, you must:

  1. Revert the UI to its previous state (or refetch the real state from the server)
  2. Show a clear error message so users understand what happened

The useOptimistic hook makes reverting automatic — when the action completes, React discards the optimistic state. Your job is catching failures and displaying feedback:

const [optimisticItems, addOptimisticItem] = useOptimistic(
  items,
  (state, newItem) => [...state, newItem]
);
const [error, setError] = useState(null);

async function handleAdd(formData) {
  const newItem = { id: crypto.randomUUID(), name: formData.get('name') };
  
  addOptimisticItem(newItem);
  setError(null); // Clear previous errors
  
  try {
    await addItemAction(formData);
    // Success: optimistic state auto-discarded, real state updates
  } catch (err) {
    setError('Failed to add item. Please try again.');
    // useOptimistic reverts automatically
  }
}

The optimistic state disappears on its own, but you control the error messaging. This keeps users informed and maintains trust.

Key Takeaway: Always wrap optimistic updates in try-catch blocks to revert UI state (handled by useOptimistic) and display meaningful error messages when server actions fail.