Skip to content

Undo and redo

A history of edits a person can step back through and forward again: two stacks, a rule for what counts as one step, and a plan for the cursor. A strong answer picks the model and explains grouping.

On this page

What it is

An undo history keeps three things: the states or changes behind you (the past), the state on screen (the present) and the steps you have undone (the future). Undo takes the last entry off the past, makes it the present, and puts the old present at the front of the future. Redo does the mirror image. Any other edit pushes the present onto the past, applies the edit, and clears the future, because the undone steps no longer describe a state that follows from the new one. This is a linear history: once you edit after undoing, the undone work is gone.

The next decision is what one entry holds. A snapshot stores a copy of the state before the edit, the memento pattern: undo swaps the snapshot back in without the history knowing anything about the edit itself. The command pattern often pairs with it: each command takes a snapshot just before it runs and restores it on undo. A patch stores the change and its inverse. Immer's produceWithPatches returns the next state, the patches that reproduce the edit and the inverse patches that revert it, and applyPatches plays either list onto a state. Since Immer 6 you turn this on once with enablePatches(). Snapshots are simple and hard to get wrong; patches cost far less memory when the state is large and each edit touches a small part of it, but an inverse that is wrong leaves the document corrupt.

ts
type Step = { redo: Patch[]; undo: Patch[]; at: number; before: Selection; after: Selection };

class History {
  private past: Step[] = [];
  private future: Step[] = [];
  private closed = true;
  constructor(private groupMs = 500) {}

  record(redo: Patch[], undo: Patch[], before: Selection, after: Selection, now = Date.now()) {
    const last = this.past[this.past.length - 1];
    if (last && !this.closed && now - last.at < this.groupMs) {
      last.redo.push(...redo);
      last.undo.unshift(...undo); // inverses run in reverse order
      last.after = after; // the group's before stays as it was
      last.at = now;
    } else {
      this.past.push({ redo, undo, at: now, before, after });
    }
    this.closed = false;
    this.future = []; // a new edit discards what was undone
  }

  close() { this.closed = true; } // on a pause, a selection move or a save

  undo(state: Doc) {
    const step = this.past.pop();
    if (!step) return null;
    this.future.push(step);
    this.closed = true;
    return { state: applyPatches(state, step.undo), selection: step.before };
  }

  redo(state: Doc) {
    const step = this.future.pop();
    if (!step) return null;
    this.past.push(step);
    return { state: applyPatches(state, step.redo), selection: step.after };
  }
}

Grouping decides what one undo reverses. Typing usually arrives as a run of small edits, and our advice is to undo the whole run at once rather than its last fragment. Editors merge edits that arrive close together: Yjs's UndoManager merges changes created within captureTimeout, 500 ms by default; setting it to 0 records each change on its own, and stopCapturing() makes the next change begin a fresh entry, which is how you close a group on a save or a selection move. Apple's guidelines ask for the option to revert a batch of related small adjustments at once, such as repeated tweaks to one property.

An entry should also carry where the person was. The same undo manager lets you attach metadata to each stack item, with the cursor position as its worked example: save it when the item is added, restore it when the item is popped. From the person's side: when an undo changes content that has scrolled off screen, bring it into view, since an undo with no visible effect tends to get repeated.

When to use it

Build a history whenever people make a run of small edits to something they care about: a text editor, a drawing canvas, a spreadsheet, a long form with reorderable rows. Apple's guidelines say people expect to undo everything since they opened the document or last saved, and warn against unnecessary limits on the number of steps. Our advice: if snapshot memory forces a cap, look first at storing patches or sharing structure between snapshots, and shorten the history as the last resort.

Decide the scope of the history up front. Redux's guide shows a single history around the whole state, or one history per part so each can be undone on its own, and redux-undo's undoable wraps one reducer, so you can give the document a history while the UI state (open panels, the active tab) stays outside it. Our advice: one history for the document and none for the chrome around it.

In a shared document, undo has to reverse your own changes and leave everyone else's in place. Yjs's UndoManager watches a set of shared types and records reverse operations for tracked changes, grouped into stack items; by default it tracks local changes made without a transaction origin, and trackedOrigins narrows that to the origins you name, so a remote peer's edits are not on your stack. A history that can undo one of your changes while later changes, including other people's, stay applied is often called selective.

Wire the entry points people already use. On macOS, people expect Undo and Redo at the top of the Edit menu, with Command-Z and Shift-Command-Z, and on iPhone a shake, so an app adds its own buttons when there is a reason, in a toolbar, with the system symbols. In a web editor built on contenteditable, the browser announces the person's intent as a beforeinput event with inputType set to historyUndo or historyRedo; the event is cancelable, so a custom editor can call preventDefault() and run its own history instead.

When not to

A plain input or textarea rarely needs a history of its own. The browser has its own undo for editing hosts, and rewriting the value from script bypasses it. MDN notes that this is the surviving reason people still call the deprecated document.execCommand(): edits made through it stay in the browser's undo buffer, while direct DOM changes do not. That is a reason to leave native fields as they are unless the history has to span several fields or an application model, not a reason to adopt execCommand, which MDN marks as deprecated and inconsistently implemented.

Keep some changes out of the history. Moving the selection, scrolling, opening a panel, or applying an update that arrived from the server should not be a step a person has to undo through. redux-undo takes a filter that decides which actions are recorded, and a hand-rolled history can skip record() for the same cases. Our advice: anything the person did not consciously do to the document stays out.

The history described here lives in the client. An action that already reached a server, a sent message, a charge, an email to a customer, is not reversed by popping a stack. To offer Undo after a delete, hold the request for a few seconds or ask the server for a soft delete; that design belongs with optimistic updates and rollback, not with the editing history.

Compared

ModelWhat a step holdsReach for it whenWhat it costs

Snapshot (memento)

A copy of the state before the edit

State is small, or immutable with structural sharing, and correctness matters more than memory

With plain copies, memory grows with state size times steps; structural sharing shrinks that to roughly what changed

Inverse patches

The change and the change that reverts it

State is large and each edit touches a small part

A wrong inverse corrupts the document; needs a patch library or careful hand-written inverses

Command objects

An object with execute() and undo(), often holding a memento

Edits are distinct operations (move shape, rename layer) with natural inverses

Each operation needs its own inverse logic; coalescing typed text is manual

Browser-native undo

The browser's own edit history for an editing host

A plain input, textarea or simple contenteditable with no custom model

Writing the value from script bypasses it; the surviving way to add steps, execCommand, is deprecated

Shared-type undo manager (Yjs)

Reverse operations for tracked local changes, grouped into stack items

The document is a Yjs shared type edited by several people

Tracks local changes without an origin unless you name origins; cursor metadata is yours to attach

In a picture

pushEditPast

Step 1 of 4

An edit pushes onto the past

Someone types hello. The history pushes the state before the edit onto the past and the new state becomes what is on screen. The future is empty.

How to say it in an interview

The common mistake

Quiz

In a linear undo history, a person undoes twice and then types a new character. What happens to the two undone steps?
A canvas holds thousands of shapes and each edit moves one of them. Which history model fits, and why?
In a shared document using Yjs, a teammate's edit arrives with a transaction origin you did not add to trackedOrigins. You press undo. What happens?
Your editor sits on a contenteditable element with its own history. The browser fires beforeinput with inputType historyUndo. What should the editor do?

Related

Sources

  1. Redux: Implementing Undo History
  2. redux-undo: higher order reducer to add undo/redo (README)
  3. Immer: Patches
  4. Yjs docs: Y.UndoManager
  5. ProseMirror reference manual: prosemirror-history module
  6. W3C Input Events Level 2
  7. Apple Human Interface Guidelines: Undo and redo (text mirrored on GitHub)
  8. Refactoring.Guru: Memento
  9. MDN: Document: execCommand() method
Sign in to report a mistake