useOptimistic: Instant UI Updates
What you'll learn: How to show immediate UI feedback while asynchronous operations complete in the background, making your app feel lightning-fast.
The Problem with Waiting
When users submit data (like a "like" button or adding a comment), waiting for the server response before updating the UI feels sluggish. Even a fast 200ms round trip creates noticeable lag that makes your app feel unresponsive.
What useOptimistic Does
useOptimistic lets you immediately show what the UI will look like after a successful action, while the actual server request happens in the background. If the server responds successfully, your optimistic update was correct. If it fails, React automatically rolls back to the previous state.
Think of it like writing a text message: it shows as "sent" instantly, then quietly confirms in the background. You don't stare at a loading spinner.
The Core Pattern
const [optimisticState, addOptimistic] = useOptimistic(
actualState,
(currentState, optimisticValue) => {
// Return what state *should* look like
return [...currentState, optimisticValue];
}
);
You render optimisticState in your UI, call addOptimistic(newValue) immediately when the user acts, then trigger your async action. When the real data arrives, actualState updates and the optimistic version disappears seamlessly.
When It Shines
Perfect for likes, comments, todos, cart additions—any mutation where failure is rare and instant feedback dramatically improves perceived performance. The user keeps working while the network catches up.
Key Takeaway: useOptimistic makes your app feel instant by showing the expected result immediately, then quietly reconciling with the server—roll back happens automatically on failure.