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
- Accessibility Patterns in ReactPractical React a11y: labels, focus management, keyboard, live regions, and composition patterns that stay accessible.
- Avoid Prop Drilling with CompositionStop threading props through intermediates: children slots, inversion of control, and when context is the right escape hatch.
- Batching State UpdatesHow React 18+ batches setState in events, timeouts, and promises: when updates flush and why double setState still works.
- Children Prop PatternsUsing children and slot props for flexible APIs: wrappers, compound components, and when to prefer explicit props.
- Client Component BoundariesWhere to put use client: push interactivity to leaves, serializable props, and children as server slots.