How to Implement Optimistic UI Updates with Rollback
Apply UI changes before the server confirms, then reconcile or roll back on failure, keeping the interface responsive and correct.
On this page
Introduction
Waiting for the server before showing a change makes an interface feel slow even when the network is fast, because every action pays a round trip. An optimistic update applies the change immediately as if it had succeeded, then reconciles with the server’s actual response or rolls back on failure. It is a small amount of state management that makes interactions feel instant, provided the rollback and reconciliation paths are handled, because a wrong optimistic update that persists is worse than a slow one.
What an Optimistic Update Is
An optimistic update predicts the outcome: when the user marks a todo done, the UI marks it done immediately, before the server confirms. The request goes out in the background, and the UI is already in the expected state. If the server agrees, nothing more happens; if it disagrees or fails, the UI rolls back or applies the server’s version.
The benefit is perceived latency: the interaction feels instant because it does not wait for the network. The risk is a wrong prediction the user sees and acts on, which is why the reconciliation and rollback must be robust and visible.
# optimistic flow
user acts -> apply the predicted change NOW (UI updates instantly)
-> send the request in the background
-> success: reconcile with the server response (usually no-op)
-> failure: roll back to the previous state, tell the user
# perception: instant; risk: a wrong prediction shown and acted on
Capturing the Previous State
A rollback needs the state before the update, so capture a snapshot before applying the predicted change. Keep the snapshot with the pending request so the rollback restores exactly what the user saw before, not a partially updated state.
For a list, capture just the affected item and its position rather than the whole list, so a rollback is a targeted change. For a value, capture the previous value. The snapshot must be immutable while the request is in flight, since other updates may be applied alongside it.
interface PendingOp<T> { id: string; previous: T; next: T; }
function applyOptimistic<T extends { id: string }>(state: T[], op: PendingOp<T>): T[] {
const snapshot = state.find((x) => x.id === op.id);
// the snapshot (previous) is kept with the op for rollback
return state.map((x) => (x.id === op.id ? op.next : x));
}
function rollback<T extends { id: string }>(state: T[], op: PendingOp<T>): T[] {
return state.map((x) => (x.id === op.id ? op.previous : x)); // restore exactly
}
Reconciling with the Server Response
On success, the server may return a different result than predicted: a server-assigned id, a computed value, a timestamp. Reconcile by replacing the optimistic value with the server’s response, so the UI converges to the truth. If the prediction was right, reconciliation is a no-op.
Reconciliation must not clobber a newer update. If two updates to the same item are in flight, apply them in order and reconcile each against its own response, so an earlier reconciliation does not overwrite a later optimistic change. Tracking a request id or a sequence number per item lets you apply the responses in order.
# on success
server response replaces the optimistic value (id, computed fields, version)
# ordering: two updates to the same item
apply them in order; reconcile each against its OWN response
# an out-of-order response must not clobber a newer optimistic change
# per-item request id / sequence lets you apply responses in order
Rolling Back on Failure
On failure, roll back to the captured previous state and tell the user. A silent rollback, where the change disappears with no explanation, is confusing; a visible error with a retry is honest. Ideally the rollback is smooth so the item returns to its place rather than flashing.
Retry policy matters: some failures are transient and a retry can succeed without bothering the user, while others (a validation error) are permanent and need the rollback and a message. Distinguish them so a network blip does not surface an error, but a rejected request does.
async function runOptimistic<T extends { id: string }>(
state: T[], op: PendingOp<T>, send: (next: T) => Promise<T>,
): Promise<T[]> {
const next = applyOptimistic(state, op); // instant UI
try {
const server = await send(op.next); // background request
return state.map((x) => (x.id === op.id ? server : x)); // reconcile
} catch (err) {
showError('Could not save; reverted'); // visible, not silent
return rollback(state, op); // restore previous exactly
}
}
Concurrency and Multiple Updates
Several optimistic updates can be in flight at once, to different items or the same one. To different items, they are independent and each rolls back on its own failure. To the same item, they need ordering: queue the updates per item, or version them so a later rollback does not undo an earlier successful change.
A common bug is rolling back to a snapshot that is stale because another update succeeded in between. Capture the previous state per operation and roll back only that operation’s change, not revert the whole item to an old value. This is why per-operation snapshots matter.
# concurrency
different items: independent; each rolls back its own change
same item: order the updates (queue per item) or version them
# do NOT roll back the whole item to a stale snapshot: an in-between
# success would be undone. Roll back only this operation's change
Where Optimism Is Apparent
Optimistic updates are appropriate for actions with a high success rate and a fast, predictable result: toggling a like, marking a read, reordering a list, adding a comment. They are inappropriate where the result depends on server logic the client cannot predict (an inventory check, a price calculation) or where a wrong result is costly.
For a prediction the client cannot make, a different pattern suits: show a pending state (a spinner on the item) rather than the predicted result, so the user sees the action is in progress without a wrong guess. Choose optimism where the prediction is reliable; use pending states where it is not.
# good for optimism (fast, predictable, high success)
toggle like, mark read, reorder, add comment
# use a pending state instead (spinner on the item)
inventory check, price/computed value, server-side validation result
# the client cannot predict => show "in progress", not a wrong guess
Common Pitfalls and Conclusion
Do not roll back silently; tell the user. Do not roll back the whole item to a stale snapshot, undoing an in-between success. Do not apply responses out of order, clobbering a newer update. And do not use optimism where the client cannot predict the result, or you show a wrong state the user acts on.
Optimistic updates make an interface feel instant by applying the predicted change before the server confirms, then reconciling or rolling back. Capture the previous state per operation, reconcile with the server response in order, roll back visibly on failure, and reserve optimism for predictable, high-success actions. Then interactions are fast without a wrong state persisting.
Sources: TanStack Query: Optimistic updates, React: useOptimistic, MDN: Optimistic UI.
FAQ
- When should I not use an optimistic update?
- When the client cannot predict the result, such as a server-side inventory check or a computed price, or when a wrong result is costly. Show a pending state on the item instead of the predicted value, so the user sees progress without a wrong guess.
- How do I avoid rolling back a newer change?
- Capture the previous state per operation and roll back only that operation's change, and apply responses in order using a per-item request id or sequence. Never revert the whole item to a stale snapshot, which would undo an in-between success.
Report a problem with this articleOpens a pre-filled issue on GitHub.