What is useOptimistic in React 19?
useOptimistic is a powerful hook for creating highly responsive "optimistic UIs". An optimistic UI immediately updates the screen to show what the user expects before the server has actually confirmed the action, making the app feel instantly fast.
How it works:
It takes the current true state from the server and an update function. It returns an "optimistic state" and an addOptimistic function.
When a user takes an action (like "Liking" a post), you call addOptimistic(newValue). React will immediately re-render using the optimistic state. While the actual background network request is happening, the user sees the immediate result. Once the network request finishes and updates the true state, React discards the optimistic state and syncs to the truth.
Error Handling:
If the network request fails, React seamlessly drops the optimistic state and reverts back to the true state, essentially undoing the action automatically.
Code example
1import React, { useState, useOptimistic } from 'react';23// Simulated server action4async function likePostAction(postId, currentLikes) {5 await new Promise(r => setTimeout(r, 1000));6 // Simulate a random server failure 20% of the time7 if (Math.random() < 0.2) throw new Error("Network failed");8 return currentLikes + 1;9}1011export default function SocialPost() {12 // 1. The True State (from the server)13 const [trueLikes, setTrueLikes] = useState(10);1415 // 2. The Optimistic Hook16 // It merges the true state with any temporary optimistic updates17 const [optimisticLikes, addOptimisticLike] = useOptimistic(18 trueLikes,19 // The update function: how the state should change optimistically20 (state, amount) => state + amount21 );2223 // 3. The Action Handler24 const handleLike = async () => {25 // A. INSTANTLY update the UI without waiting for the server26 addOptimisticLike(1);2728 try {29 // B. Actually perform the slow server request30 const newTrueLikes = await likePostAction('post-123', trueLikes);31 // C. Update the true state upon success32 setTrueLikes(newTrueLikes);33 } catch (error) {34 // D. If it fails, we don't update the true state.35 // React will automatically revert 'optimisticLikes' back to 'trueLikes'36 console.error("Failed to like post");37 }38 };3940 return (41 <div className="p-6 border rounded-2xl max-w-sm bg-white shadow-sm">42 <h3 className="text-xl font-bold mb-2">Just launched my new app! 🚀</h3>43 <p className="text-slate-500 mb-6">It's incredibly fast thanks to React 19.</p>4445 {/* We display the optimistic state so the UI feels instant */}46 <form action={handleLike}>47 <button48 type="submit"49 className="flex items-center gap-2 px-4 py-2 bg-pink-50 text-pink-600 rounded-full font-bold hover:bg-pink-100 transition-colors"50 >51 ❤️ {optimisticLikes} Likes52 </button>53 </form>54 </div>55 );56}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React Hooks set.