Like buttons that don't wait for the server
How React 19's useOptimistic shows the result first, rolls back on its own when the request fails, and where it shouldn't be used.
By Moshiur Rahman2 min readReact, UX
A like button that waits 900ms for the server feels broken, even when it works.
Both hearts below talk to the same pretend server. The left one waits for the response before it fills in. The right one uses useOptimistic. Raise the latency, then turn on Make requests fail and click the right one again.
What useOptimistic does
You pass it the real state, and it gives you back a value you can change inside a transition:
const [liked, setLiked] = useState(false)
const [optimisticLiked, setOptimisticLiked] = useOptimistic(liked)While the transition is pending, React renders your optimistic value. When the transition ends, React goes back to rendering the real state, whatever it is by then.
const [isPending, startTransition] = useTransition()
const toggle = () => {
const next = !optimisticLiked
startTransition(async () => {
setOptimisticLiked(next) // shows right away
await saveLike(next)
startTransition(() => setLiked(next)) // make it real
})
}
return <Heart filled={optimisticLiked} />The second startTransition is there because state updates after an await aren't part of the transition anymore, so React's docs say to wrap them again.
Failures roll back by themselves
That last part handles errors for you. If saveLike throws, setLiked never runs. The transition still ends, React drops the optimistic value, and the heart un-fills because the real state is still false. You don't write any rollback code.
Tell people when it happens
The silent un-fill is confusing. People see the heart empty itself and assume they misclicked. Catch the error and say what happened:
try {
await saveLike(next)
startTransition(() => setLiked(next))
} catch {
setError("Couldn't save your like.")
}That's what the message under the right button is in the demo.
Where it fits
Optimistic UI shows a "yes" before the server has said yes. That's fine when being wrong for a second is harmless: likes, saves, bookmarks, adding a todo, reordering a list.
It doesn't fit where showing success that didn't happen costs something. Payments, deleting things and sending messages should wait for the server, with a pending state that makes the wait clear.
Further reading
The useOptimistic reference on react.dev covers the reducer form, useOptimistic(state, updateFn), for lists where several optimistic updates stack. The like-button example outside a form was added to the docs in reactjs/react.dev#6463.
Need this on your site?
I build interfaces like this for agencies, startups and SaaS teams.
Let's talk