Deviopath › Next.js

Optimistic Like Button

Medium · Server Actions

A Server Action takes a moment to answer. Instead of making the user wait, show the expected result right away and correct it later. React 19's useOptimistic does exactly that:

``tsx const [optimisticLikes, addOptimisticLike] = useOptimistic(likes, (current, amount: number) => current + amount); ``

Call addOptimisticLike(1) **inside a transition** (startTransition from useTransition). While the transition runs, optimisticLikes shows the optimistic value. When it ends, React switches back to the real likes state, so if the action failed and you never updated likes, the optimistic change disappears by itself (automatic rollback).

A state update after an await inside a transition must be wrapped in startTransition again, so it is applied together with the end of the transition.

The fake server action saveLike is already written. Update LikeButton:

- Show Likes: <optimisticLikes> in the .count paragraph. It should show the new count **immediately** after a click.

- While saving, show <span className="status">Saving…</span> and disable the Like button.

- On success, store the confirmed total from the action in likes.

- On failure, show <p className="error">Could not save your like</p>; the count goes back to the confirmed value. Clear the error on the next click.

Next: cacheLife Profiles