Skip to content
fa
Search Frontend Atlas
Search questions and concepts across the handbook.
UI Engineering & Machine Codingadvanced13 min read

How do you implement optimistic UI without corrupting client state?

Treat optimistic updates as speculative transactions with reconciliation, rollback, and concurrency rules.

Useful prerequisites

A user clicks ‘Like’ and expects the button to respond immediately. Waiting for the server round trip makes the interface feel sluggish, so an application can update the screen first and send the request in the background. That is an optimistic update; the hard part is deciding what to do if the server rejects it or another update arrives first.

A user clicks ‘Like’ and expects the button to respond immediately. Waiting for the server round trip makes the interface feel sluggish, so an application can update the screen first and send the request in the background. That is an optimistic update; the hard part is deciding what to do if the server rejects it or another update arrives first.

The quick version

Apply a reversible local change, send the mutation, then reconcile with the authoritative response. On failure, restore or invalidate the affected state. Serialize or version overlapping mutations when order matters.

Build the mental model

A naive rollback can overwrite a newer successful change. Capture a mutation ID or prior version, and only roll back if the optimistic version is still current. Idempotency keys help the server deduplicate retried mutations.

See it in code

const mutationId = crypto.randomUUID();
applyOptimistic(change, mutationId);
try {
  reconcile(await save(change), mutationId);
} catch (error) {
  rollbackIfCurrent(mutationId);
  throw error;
}

Where it gets tricky

Suppose mutation A and mutation B both update the same record. If A fails after B succeeds, blindly restoring A’s old snapshot erases B. Associate optimistic writes with mutation/version identity and only roll back the state still owned by that mutation. Reconcile from authoritative server data after success, especially when the server normalizes values.

A common misunderstanding

“Undo the previous value on error” is unsafe when concurrent updates are possible.

What this changes in an application

Define conflict behavior, retry semantics, offline behavior, and user-visible pending/error states before shipping optimistic interactions.

Questions worth exploring next

  • What if two saves race?
  • How do you handle a server response arriving out of order?

References and next steps

  • Optimistic updates — primary or authoritative documentation for the underlying behavior.
  • MDN Web Docs — use the relevant API reference for adjacent browser details.

Explore next