Skip to the page

React 19.x: Actions, forms and Server Components · senior

useOptimistic: instant UI with automatic rollback

useOptimistic(value, reducer?) shows a temporary value while an Action is pending and automatically goes back to the real value when the Action finishes, so a failed request rolls back without extra code.

The notes

What you must know

  • const [optimisticLikes, addOptimistic] = useOptimistic(likes, (current, delta) => current + delta); inside an Action: addOptimistic(1); await likePost(); setLikes(serverCount).
  • The optimistic state only exists while the Action/transition is pending. When it ends, React renders with whatever value is now, in the same render (no extra "clear" render).
  • On failure the parent never updated value, so the UI returns to the old number automatically; catch the error to show a message.
  • The setter must be called inside an Action or startTransition; outside, React warns and the value flashes and reverts.
  • Use the reducer form when the base value can change while the Action is pending (lists, counts).
  • Make the server operation idempotent (send "liked = true", not "+1"), and guard against rapid double clicks (disable or queue per item).
  • TanStack Query equivalent: onMutate (cancel queries, snapshot, setQueryData), onError (restore snapshot), onSettled (invalidate). Or show pending items from mutation variables without touching the cache.

The red pen

Common traps: mistake → fix

  • Mistake: "Optimistic means no rollback code needed anywhere"

    Fix: you still show an error and keep the server as the source of truth.

  • Mistake: "Trust the client count"

    Fix: the server returns the real count.

  • Mistake: "Call the optimistic setter in a plain onClick"

    Fix: it must be inside a transition/Action.

Easy to hard

Questions interviewers ask, easy to hard

  1. Build an optimistic Like button that rolls back if the server fails.
  2. How does useOptimistic know when to drop the optimistic value?
  3. Rapid double clicks: how do you avoid count drift?
  4. How would you do it with TanStack Query or RTK Query?
  5. How do you show the failure to the user?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview