Optimistic UI & Rollback Safety
Optimistic UI renders the expected post-mutation state immediately at 0 ms instead of trapping the user behind a spinner. To avoid corrupting the screen when requests fail or arrive out of order, keep confirmed server state separate from the speculative overlay and restore the snapshot on error.
Optimistic Mutation: Snapshot, Speculate & Rollback
Step through cancelling stale refetches, applying an optimistic overlay, and rolling back on 500 error.
Before mutating, cancel any in-flight GETs so a stale response can't overwrite the optimistic UI.
const prev = cache.get(['post', id]);
await queryClient.cancelQueries(['post', id]);- confirmedLikes
- 41
- displayLikes
- 41
- pendingRequests
- 0
Under the Hood
Optimistic UI works like an accountant's pencil-and-ink ledger: you write the expected balance in pencil right away so the customer sees instant feedback for Core Web Vitals INP, and only ink it over (or erase it) once the bank clears the check.
- Cancel in-flight reads: Abort or ignore any running
GETrefetch for the same entity so an older server payload cannot clobber the new optimistic state. - Snapshot & overlay: Save the last confirmed value (or use
useOptimistic, which overlays temporary state over base props without mutating them) and avoid Stale Closures by reading from a functional reducer. - Reconcile or rollback: On
200 OK, replace the speculative entry with the server's authoritative record; on4xx/5xx, revert to the snapshot and surface an explicit retry action.
async function toggleLike(postId, nextLiked) {
const snapshot = store.get(postId);
store.set(postId, { ...snapshot, liked: nextLiked, pending: true });
try {
const confirmed = await api.setLike(postId, nextLiked);
store.set(postId, confirmed);
} catch (err) {
store.set(postId, snapshot); // Atomic rollback on failure
notifyRetry('Could not save like', () => toggleLike(postId, nextLiked));
}
}Problem Genealogy
- 2005 (Spinner-Driven AJAX): Blocked buttons with loading spinners for every 300 ms
POST, making web apps feel sluggish compared to desktop software. - 2014 (Client Cache Stores, Relay/Apollo): Normalized entity graphs and introduced optimistic response patches, often tangled with manual rollback bugs.
- 2023+ (
useOptimistic& Scoped Mutations): Built ephemeral overlay semantics directly into UI runtimes so failed mutations auto-discard when transitions settle.
Production Pitfalls
- Out-of-order toggle races: Rapidly clicking Like -> Unlike fires two requests; if Request #1 resolves slower than Request #2, naive reconciliation flickers the UI back to Liked. Use a monotonic request counter or
AbortController. - Fake IDs leaking into URLs: Creating a comment optimistically with
id: "temp-123"and letting the user click/comments/temp-123before the server assigns a real ID breaks deep links.
- When not to use Optimistic UI: Never fake success on irreversible or high-stakes actions, payment charges, inventory reservations, password changes, or destructive account deletions; for local multi-step editing history, use Undo/Redo & Structural Sharing instead.
Connections & Logical Next Steps
Queued mutations apply optimistic UI updates immediately and reconcile or roll back when the outbox drains.
UI mutations wrap Server Action invocations in optimistic state that rolls back if the RPC rejects.
Rollback handlers must avoid closing over stale pre-mutation state when rapid consecutive edits occur.
Immediate optimistic state transitions keep perceived latency and INP presentation under 16 ms.
Modeling pending, confirmed, and rolled-back phases as finite states prevents double-mutations.
Optimistic rollback reverts failed pending mutations, whereas undo/redo tracks user-confirmed history via structural sharing.
Optimistic UI rolls back if the server rejects; Local-First treats local storage as primary and merges via CRDTs.
Mechanical Comparisons
Optimistic UI rolls back if the server rejects; Local-First treats local storage as primary and merges via CRDTs.
Optimistic rollback reverts failed pending mutations, whereas undo/redo tracks user-confirmed history via structural sharing.