useOptimistic is a React 19 hook for optimistic UI updates: you show the result immediately, and if the server returns an error — you roll back.
Simple analogy: Imagine you are liking a post on Instagram.
How it works:
1import { useOptimistic } from 'react';23function LikeButton({ postId, initialLikes }) {4 const [optimisticLikes, addOptimisticLike] = useOptimistic(5 initialLikes, // Current state6 (state, newLike) => state + 1 // Optimistic update function7 );89 async function handleLike() {10 addOptimisticLike(); // Immediately show +11112 try {13 await api.likePost(postId);14 } catch (error) {15 // If error — React will automatically roll back the optimistic update16 showError('Failed to like');17 }18 }1920 return <button onClick={handleLike}>❤️ {optimisticLikes}</button>;21}
Where it is used:
Important: Always handle errors and roll back changes if the server did not respond successfully.