Skip to content

useOptimistic

Medium — good to knowFrontend

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."

Made with passive-aggressive love by manoga.digital. Powered by Claude.