Dev Overflow Logo

Dev Overflow

Global search

Search across questions, answers, users and tags.

Loading...
save

How do I handle optimistic UI updates that fail on the server?

clock icon

asked 2 months ago

message icon

2

eye icon

578

Upvote buttons feel sluggish when I wait for the round trip, but if I update immediately and the request fails, the UI lies. What is the accepted pattern in a Next.js app using server actions?

2 Answers

useOptimistic is built for exactly this, and the rollback is automatic:

1const [optimisticVotes, addOptimistic] = useOptimistic(
2 votes,
3 (state, delta: number) => state + delta,
4)
5
6async function handleUpvote() {
7 addOptimistic(1)
8 await upvoteAction(questionId) // throws → optimistic state is discarded
9}
1const [optimisticVotes, addOptimistic] = useOptimistic(
2 votes,
3 (state, delta: number) => state + delta,
4)
5
6async function handleUpvote() {
7 addOptimistic(1)
8 await upvoteAction(questionId) // throws → optimistic state is discarded
9}

When the action settles, React re-renders from the real state. If it failed, the real state never changed and the optimistic value simply disappears — you don't hand-roll the undo.

Do still surface the failure with a toast. Silently reverting a number the user just watched go up is worse than saying "couldn't save that".

Also make the server action idempotent where you can. Users double-click, and a vote endpoint that toggles on every call turns a double-click into no vote at all.

1

of 1

Write your answer here

Introduce the problem and expand on what you've put in the title.

Top Questions