# Optimistic UI & Rollback Safety vs Undo/Redo & Structural Sharing

- **Canonical URL:** https://frontend.rocks/vs/optimistic-ui-rollback-vs-undo-redo-structural-sharing/
- **Relation:** Contrasts With
- **Last Verified:** 2026-11-15
- **Verdict:** Optimistic rollback reverts failed pending mutations, whereas undo/redo tracks user-confirmed history via structural sharing.

## Comparison Matrix

| Dimension | Optimistic UI & Rollback Safety | Undo/Redo & Structural Sharing |
| :--- | :--- | :--- |
| **Maturity** | Baseline · Widely | Baseline · Widely |
| **Domain** | State & Architecture | State & Architecture |
| **Mental Model** | Applies speculative UI state immediately on user action while retaining an immutable confirmed snapshot for atomic rollback if the network request fails. | Implements O(1) undo/redo stacks without deep-cloning megabytes of state by copy-on-write cloning only the modified ancestor path and reusing untouched subtree pointers. |
| **Prerequisites** | Stale Closures in Hooks & Callbacks (Rollback handlers must avoid closing over stale pre-mutation state when rapid consecutive edits occur.) | None |
| **When Not to Use** | When not to use Optimistic UI: Never fake success on irreversible or high-stakes actions, payment charges, inventory reservations, password changes, or destructive account deletions; for local multi-step editing history, use Undo/Redo & Structural Sharing instead. | When not to use Structural Sharing: For 2D pixel buffers or 100k-row typed arrays, copy-on-write still duplicates large Uint8Array chunks, store compact inverse command deltas instead. |

## Optimistic UI & Rollback Safety — Under the Hood
Optimistic UI works like an accountant's pencil-and-ink ledger: you write the expected balance in pencil right away so the customer sees instant feedback for [Core Web Vitals](/concepts/core-web-vitals-mechanics) INP, and only ink it over (or erase it) once the bank clears the check.

1. **Cancel in-flight reads**: Abort or ignore any running `GET` refetch for the same entity so an older server payload cannot clobber the new optimistic state.
2. **Snapshot & overlay**: Save the last confirmed value (or use `useOptimistic`, which overlays temporary state over base props without mutating them) and avoid [Stale Closures](/concepts/stale-closures-hooks) by reading from a functional reducer.
3. **Reconcile or rollback**: On `200 OK`, replace the speculative entry with the server's authoritative record; on `4xx`/`5xx`, revert to the snapshot and surface an explicit retry action.

```js
async function toggleLike(postId, nextLiked) {
  const snapshot = store.get(postId);
  store.set(postId, { ...snapshot, liked: nextLiked, pending: true });
  try {
    const confirmed = await api.setLike(postId, nextLiked);
    store.set(postId, confirmed);
  } catch (err) {
    store.set(postId, snapshot); // Atomic rollback on failure
    notifyRetry('Could not save like', () => toggleLike(postId, nextLiked));
  }
}
```

## Undo/Redo & Structural Sharing — Under the Hood
Structural sharing works like Git commits: editing one file creates new tree nodes only along its parent folders, while sibling folders share the exact same pointers. Keeping unchanged subtrees `===` identical lets [Virtual DOM](/concepts/virtual-dom-reconciliation) bail out in $O(1)$ and preserves [V8 Hidden Classes](/concepts/v8-hidden-classes-ic).

1. Store history as `{ past: State[], present: State, future: State[] }`.
2. On edit, copy only the modified path (`{ ...state, nodes: { ...state.nodes, [id]: nextNode } }`), push `present` onto `past`, and reset `future = []`.
3. On `undo()`, pop `past` into `present` and push old `present` onto `future`, zero object cloning required.

```js
function commitEdit(history, nextPresent) {
  return {
    past: [...history.past.slice(-99), history.present], // Cap stack at 100
    present: nextPresent,
    future: [], // Clear redo branch on new timeline
  };
}
```

## Interactive Labs & Dissections
- [Optimistic UI & Rollback Safety Lab](https://frontend.rocks/concepts/optimistic-ui-rollback/#lab) ([Markdown](https://frontend.rocks/concepts/optimistic-ui-rollback.md))
- [Undo/Redo & Structural Sharing Lab](https://frontend.rocks/concepts/undo-redo-structural-sharing/#lab) ([Markdown](https://frontend.rocks/concepts/undo-redo-structural-sharing.md))

## Primary Sources
- https://react.dev/reference/react/useOptimistic
- https://tanstack.com/query/latest/docs/framework/react/guides/optimistic-updates
- https://web.dev/articles/inp
- https://immerjs.github.io/immer/structural-sharing/
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy
- https://developer.mozilla.org/en-US/docs/Web/API/Window/structuredClone
