useOptimistic
ELI5 - The Vibe Check
useOptimistic lets your UI lie a little, in a good way. You click like on a post and the heart turns red instantly, before the server has even confirmed it. If the request fails, React quietly rolls the fake state back. It's the hook version of a waiter saying sure, coming right up, before checking whether the kitchen actually has the dish.
Real Talk
useOptimistic is a React hook that lets you show an optimistic state during an async action, temporarily overriding the actual state until the action settles. It takes the current state and an update function, and automatically reverts to the real state once the underlying action resolves or fails.
Show Me The Code
function LikeButton({ postId, likes }) {
const [optimisticLikes, addOptimisticLike] = useOptimistic(
likes,
(state) => state + 1
);
async function like() {
addOptimisticLike();
await likePost(postId);
}
return <button onClick={like}>{optimisticLikes} likes</button>;
}
When You'll Hear This
"The like button feels instant now that we wrapped it in useOptimistic." / "useOptimistic reverted the comment when the server rejected it, so the UI never lied for long."
Related Terms
Optimistic UI
Optimistic UI means updating the interface BEFORE the server confirms the action succeeded. Click 'Like'? The heart turns red immediately.
React
React is a JavaScript library from Meta for building UIs out of components.
Server Actions
Server Actions let you write a function in your React component that magically runs on the server when called.
useActionState
useActionState is React's way of handling I submitted a form, now what, without a pile of useState calls for loading, errors, and results.