Dev.Lib
arrow_backBack to Blogs
LEVEL_044.8June 27, 20261 min read

Optimistic UI rollback strategy

State & Data Flow

Apply UI change before server confirms; on failure revert and notify.

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 / onError pattern.
  • Never optimistic-delete without undo path.

Further reading

Related concepts