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.
โก Interactive Playground
Stuck on a Complex Codebase or Preparing for Senior Dev Interviews?
Whether you need urgent sprint job support to fix stubborn bugs in production, architectural guidance for your enterprise app, or targeted 1:1 mentorship to land a senior role โ get real-time screen-share assistance.
1:1 Deep-Dive Mentorship
Weekly 1-on-1 live coding, design pattern reviews, and customized roadmaps in React, Node, TS, Playwright, and Mongo.
Live IT Job & Sprint Support
Urgent on-demand screen-share assistance to unblock sprint deliverables, debug memory leaks, and optimize slow queries.
FAANG Mock Coding Rounds
Simulated machine coding rounds with line-by-line code reviews, rubric scoring, and Google X-Y-Z resume optimization.