Frontend Case Studies

Topic F10

Undo and redo

Two stacks for undo and redo, and why a new action wipes redo.

8 min · beginner

Watch: every action goes on the left pile. Undo moves it to the right pile; redo moves it back.

undo stackredo stackdocument(empty)
  • moving now
  • finished / the result
  • no longer used
Step 1 of 9

A text editor with two stacks. Every action goes on the undo stack. Undo moves the last action onto the redo stack.

Undo reverses the latest action first. That's exactly how a stack works.

What to store: actions or snapshots

  • Snapshots: store a copy of the whole state after each change. Undo just goes back to the previous copy. Very simple, and cheap if the state is immutable (copies share the unchanged parts), but wasteful for big documents.
  • Commands: store the action and how to reverse it ("insert 'a' at position 5" and its inverse "delete 1 character at position 5"). Memory-light, but every kind of action needs a correct inverse.
Code, for programmersSnapshot undo in React
function useHistory(initial) {
  const [h, setH] = useState({ past: [], present: initial, future: [] });
  return {
    value: h.present,
    set: (next) => setH(({ past, present }) =>
      ({ past: [...past, present], present: next, future: [] })),   // new action: clear redo
    undo: () => setH(({ past, present, future }) => past.length === 0 ? { past, present, future } :
      ({ past: past.slice(0, -1), present: past[past.length - 1], future: [present, ...future] })),
    redo: () => setH(({ past, present, future }) => future.length === 0 ? { past, present, future } :
      ({ past: [...past, present], present: future[0], future: future.slice(1) })),
  };
}

Details people forget

  • Grouping: typing "hello" should be one undo step, not five. Merge nearby keystrokes (say under 500 ms apart), much like debounce.
  • A limit: keep, say, the last 100 steps and drop the oldest, so memory doesn't grow forever.
  • What can't be undone: a payment or a sent email can't be reversed in the browser. For those, delay the action a few seconds with an "Undo" message (as Gmail does), or create a compensating action on the server.
  • Collaboration: in shared editors (Google Docs, Figma), undo only reverses your own actions, not other people's. That needs much more elaborate structures (OT or CRDTs).

Quiz

  1. Type a, b, c, then undo twice. What's on the redo stack (top first)?

  2. After an undo, the user types a new letter. What happens to the redo stack?

  3. Why should typing 'hello' be one undo step?

0 of 3 answered.