tezvyn:

Optimistic UI updates for actions

AI-drafted, machine-checkedSource: interviewadvanced
WHAT IT TESTS

perceived-performance technique with rollback.

OUTLINE

update UI immediately on the assumption of success, send the request, then confirm or roll back on failure.

RED FLAG

applying optimistic state without any rollback or error path.

WHAT THIS TESTS Whether you can trade certainty for responsiveness safely, which hinges entirely on a correct rollback path, not just the happy case.

A GOOD ANSWER COVERS Optimistic UI updates the interface immediately, assuming the mutation will succeed, so interactions feel instant despite network latency. The essential steps are: capture the current state as a snapshot, apply the optimistic change locally, issue the server request, and then reconcile. On success you confirm, optionally replacing optimistic values with authoritative server data. On failure you restore the snapshot and surface a brief, non-blocking error so the user understands the action did not stick. React's useOptimistic hook formalizes this by deriving optimistic state that automatically reverts when the underlying action settles, and Apollo and React Query offer optimisticResponse and onMutate with rollback hooks.

COMMON WRONG ANSWERS Applying the optimistic change with no rollback, so a failed request leaves a like that the server never recorded; not snapshotting prior state so revert is impossible; double-counting when a slow real response also increments; or blocking the UI with a spinner, which defeats the purpose.

LIKELY FOLLOW-UPS How does useOptimistic differ from manual useState rollback? How do you reconcile the optimistic value with the server's authoritative count? How do you debounce rapid toggles?

ONE CONCRETE EXAMPLE Tapping like immediately flips liked to true and increments the count from 41 to 42, then POSTs to the server. If the POST succeeds, the optimistic state stands or is replaced by the returned count. If it fails, the code restores liked to false and the count to 41 and shows 'Couldn't like, try again'. With useOptimistic, the optimistic 42 reverts automatically once the failed action resolves, without manual snapshot bookkeeping.

Read the original → react.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.