Community JavaScript Snippet

useOptimisticMutation Hook With Rollback

My take on optimistic UI before React 19's `useOptimistic` was usable. The hook applies the change locally, fires the network call, and rolls back on failure with the original snapshot intact.

useOptimisticMutation Hook With Rollback

My take on optimistic UI before React 19's `useOptimistic` was usable. The hook applies the change locally, fires the network call, and rolls back on failure with the original snapshot intact.

JavaScript
Frontend
4 snippets
react
hooks
error-handling
optimistic-ui
laylabauer

By @laylabauer

January 28, 2026

·

Updated May 18, 2026

582 views

8

4.7 (9)

I always start optimistic UI with a state machine because the rollback logic gets ugly fast otherwise. Three fields matter: data (what the UI shows), snapshot (what we restore on error), and status (so the button can disable itself during pending). Capturing the snapshot at submit time, not at error time, is the key invariant: if a second mutation interleaves the response, we still know what to roll back to. A pure reducer like this can be tested with five lines of vitest and shared between hooks if you need an useOptimisticForm and an useOptimisticToggle later.