Optimistic UI Updates
Optimistic UI updates the screen before the server confirms: apply, rollback on error, and concurrent-safe patterns.
- react
- optimistic-ui
Optimistic UI assumes the mutation will succeed and updates local state immediately. When the server fails, you roll back and show an error. Done well, apps feel instant; done poorly, users see ghost data and lost trust.
Docs: useOptimistic (React 19), classic manual patterns below.
Manual pattern
function LikeButton({ postId, initialCount }) {
const [count, setCount] = useState(initialCount);
const [error, setError] = useState(null);
async function like() {
setError(null);
setCount((c) => c + 1); // optimistic
try {
await fetch(`/api/posts/${postId}/like`, { method: 'POST' });
} catch (e) {
setCount((c) => c - 1); // rollback
setError('Could not like. Try again.');
}
}
return (
<>
<button type="button" onClick={like}>Like ({count})</button>
{error && <p role="alert">{error}</p>}
</>
);
}
useOptimistic sketch
const [optimisticLikes, addOptimistic] = useOptimistic(
likes,
(state, newLike) => state + 1
);
Frameworks wire this with Server Actions / transitions so the optimistic state is tied to an in-flight request.
Rules that keep you honest
- Idempotent-friendly mutations when users double-click.
- Rollback that restores previous truth, not a guessed value.
- Conflict policy when server returns a different final state (use server as source of truth on settle).
- Accessibility: announce failures; do not only change color.
- Lists: optimistically insert with a temporary client id, then replace with server id.
When not to be optimistic
Payments, irreversible deletes without undo, or multi-step server validation where failure is common. Prefer pending UI and disable the control.
Interview out-loud
“Optimistic UI updates local state before the server responds, then commits or rolls back. I keep the last confirmed server state for rollback, handle double-submit, and avoid optimism for irreversible money moves. React 19 useOptimistic formalizes the pattern with transitions.”
Related on this site
Further reading
Edge cases worth rehearsing
Interviewers and production incidents cluster around the same edges: first render versus update, empty and loading states, Strict Mode double setup, concurrent interruptions, and what happens when identity (key, route params, user id) changes mid-edit. Walk one concrete user journey end-to-end — open, edit, navigate away, come back — and say which state survives.
Prefer fixing data flow and ownership before reaching for memoization or micro-optimizations. Prefer event handlers over effects when a user action is the trigger. Prefer deriving values during render over mirroring props into state. Prefer stable list keys from business ids. Measure with the profiler when performance is the claim.
When you cite an API, mention one failure mode: abort on unmount, serializable props across server/client boundaries, focus restoration for dialogs, or cache invalidation after a mutation. Specific beats generic every time.
Edge cases worth rehearsing
Interviewers and production incidents cluster around the same edges: first render versus update, empty and loading states, Strict Mode double setup, concurrent interruptions, and what happens when identity (key, route params, user id) changes mid-edit. Walk one concrete user journey end-to-end — open, edit, navigate away, come back — and say which state survives.
Prefer fixing data flow and ownership before reaching for memoization or micro-optimizations. Prefer event handlers over effects when a user action is the trigger. Prefer deriving values during render over mirroring props into state. Prefer stable list keys from business ids. Measure with the profiler when performance is the claim.
When you cite an API, mention one failure mode: abort on unmount, serializable props across server/client boundaries, focus restoration for dialogs, or cache invalidation after a mutation. Specific beats generic every time.
Related guides
- useCopyToClipboard HookCopy text with navigator.clipboard, fallback execCommand, transient copied state, and permissions that fail in insecure contexts.
- useDebouncedValue HookDebounce a changing value in React without firing effects on every keystroke. Cleanup, leading vs trailing, and the stale timer that updates unmounted state.
- useEventListener HookAttach a window, document, or element listener with a stable handler ref so you do not rebind on every render. Capture option and target changes.
- useFetch With AbortControllerFetch in an effect with a signal, ignore aborted errors, and prevent the slow response from winning a race after the url changes.
- useIdle HookDetect idle users: reset a timer on input events, fire idle after timeout, and decide whether mount starts the timer immediately.