Summary
Apply UI change before server confirms; on failure revert and notify. Requires idempotent server ops or conflict handling. Queue mutations offline with rollback on sync failure. TanStack Query onMutate / onError pattern. Never optimistic-delete without undo path.
Code example
async function toggleLike(postId) {
const previous = likes[postId];
setLikes({ ...likes, [postId]: !previous }); // optimistic
try {
await api.like(postId);
} catch {
setLikes({ ...likes, [postId]: previous }); // rollback
toast.error('Could not save like');
}
}
Key points
- Apply UI change before server confirms; on failure revert and notify.
- Requires idempotent server ops or conflict handling.
- Queue mutations offline with rollback on sync failure.
- TanStack Query
onMutate/onErrorpattern. - Never optimistic-delete without undo path.