patternModeratepending
Optimistic UI updates -- instant feedback with rollback
Viewed 0 times
optimistic updaterollbackinstant feedbackperceived performancelike button
Problem
Waiting for server response before updating the UI feels slow. Users click a like button and wait 200-500ms before seeing the change. Perceived performance suffers.
Solution
Update the UI immediately (optimistically) before the server responds. If the server confirms success, keep the update. If it fails, roll back to the previous state and show an error. Implementation: (1) Save previous state. (2) Apply optimistic update. (3) Send request to server. (4) On success: do nothing (UI is already correct). (5) On failure: restore previous state, show error toast. Works great for: likes, toggles, drag-and-drop reorder, form submissions.
Why
Most server operations succeed. Optimistic updates make the common case instant while handling the rare failure gracefully. This dramatically improves perceived performance.
Code Snippets
Optimistic UI update with rollback
// React optimistic update
function useLike(postId) {
const [liked, setLiked] = useState(false);
const [pending, setPending] = useState(false);
const toggle = async () => {
const prev = liked;
setLiked(!liked); // optimistic
setPending(true);
try {
await api.toggleLike(postId);
} catch {
setLiked(prev); // rollback
toast.error('Failed to update');
} finally {
setPending(false);
}
};
return { liked, toggle, pending };
}Revisions (0)
No revisions yet.