Click. Done. (Then Network)
When you like a tweet, does it wait for the server? No. The heart turns red instantly.
If your app shows a spinner for a boolean toggle, you are failing your users. React 19 gives us a primitive to fix this.
The Old Way: You have local state isLiked. When clicked, you set it to true. Then you fire the API. If it fails, you set it back to false. Managing three states (true, false, loading) manually is pain.
The New Way: useOptimistic lets you declare what the UI should look like while an async action is pending. It handles the switch, the display, and the rollback automatically.
02. Understanding useOptimistic
const [optimisticState, addOptimistic] = useOptimistic(
state, // Source of Truth (Server Data)
// Reducer: How to merge optimistic updates
(currentState, optimisticValue) => {
return [...currentState, optimisticValue];
}
);
It takes two main arguments: the current real state (usually from props/server) and a reducer function.
When you call addOptimistic, React immediately re-renders with the result of your reducer. Once the async action finishes (and the new real state arrives via props), React automatically discards the optimistic state and uses the real one.