Memento Pattern (Undo/Redo) — Design Patterns

Memento keeps a snapshot of the state before each change so it can be brought back. Its three roles: the originator (form, with save and restore), the memento…

An admin changes the address on a shipment form, then realises it's wrong and presses Ctrl+Z. How does the app know what the form held before the change? From a snapshot taken before it.

The Memento pattern keeps a snapshot of an object's state before the object changes, so that state can be brought back later. It's the base of every undo and redo button. Picture taking apart a bicycle brake. Before you start, you take a photo of it. If the reassembly goes wrong, the photo shows how to put it back. You don't scribble on the photo, you keep it in an album, and when your phone runs out of space, the oldest photo is the one deleted.

The problem: a form with no way back

The shipment draft form holds the recipient, the service, the weight and the address. The admin changes the service to express, then the city to Bath, then realises both were wrong. If the old state wasn't kept anywhere, there's nothing to bring back.

In the Command lesson, each action kept how to cancel itself. For a form with many fields, that means writing an inverse for every field. Memento takes a simpler route: before every change, keep the whole draft.

Three roles: originator, memento, caretaker

// Originator: the form that makes and restores snapshots
const form = {
  draft: {
    recipient: "Mrs. Sari",
    service: "regular",
    kg: 2,
    address: { street: "5 Jasmine Street", city: "Bristol" },
  },
  save() {
    return structuredClone(this.draft) // memento: a full copy, address copied too
  },
  restore(memento) {
    this.draft = structuredClone(memento)
  },
}

// Caretaker: keeps the snapshots, never changes what is inside
const MAX_HISTORY = 5
const history = { undo: [], redo: [] }

function edit(field, change) {
  history.undo.push(form.save()) // save BEFORE the change
  if (history.undo.length > MAX_HISTORY) history.undo.shift() // drop the oldest
  history.redo.length = 0 // a new edit cancels redo
  change(form.draft)
}

function undo() {
  if (history.undo.length === 0) return false
  history.redo.push(form.save())
  form.restore(history.undo.pop())
  return true
}

function redo() {
  if (history.redo.length === 0) return false
  history.undo.push(form.save())
  form.restore(history.redo.pop())
  return true
}

function summary(d) {
  return d.service + ", " + d.kg + " kg, " + d.address.city
}

Undo and redo, step by step

edit("service", (d) => { d.service = "express" })
edit("city", (d) => { d.address.city = "Bath" })
undo()
undo()
redo()
edit("weight", (d) => { d.kg += 1 })
console.log(redo()) // false
step the draft after it in the undo stack in the redo stack
start regular, 2 kg, Bristol 0 0
edit("service", ...) express, 2 kg, Bristol 1 0
edit("city", ...) express, 2 kg, Bath 2 0
undo() express, 2 kg, Bristol 1 1
undo() regular, 2 kg, Bristol 0 2
redo() express, 2 kg, Bristol 1 1
edit("weight", ...) express, 3 kg, Bristol 2 0
redo() false, the draft doesn't change 2 0

Undo puts the current draft on the redo stack, then restores the top snapshot from the undo stack. Redo does the opposite. When a new edit comes after an undo (edit("weight")), the redo stack is emptied. That edit starts a new branch, so the "express, 2 kg, Bath" snapshot in redo doesn't fit anymore: redoing to it would throw away the weight that was just changed. Undo in text editors and design apps behaves the same way.

A shallow copy: a snapshot that changes too

Now save() is written with spread:

save() {
  return { ...this.draft } // a shallow copy
},
restore(memento) {
  this.draft = { ...memento }
},

Take a guess first. The shipment draft has address: { street: "5 Jasmine Street", city: "Bristol" }, and its snapshot is made with { ...this.draft }. The admin changes the city to Bath (d.address.city = "Bath"), then presses undo. Which city shows?

Run edit("city", ...) then undo(), and the city stays Bath. { ...draft } only copies the top fields. service and kg hold a string and a number, so their values are copied. But address holds an object, and only its reference is copied: the snapshot and the draft hold the same address object. d.address.city = "Bath" changes that object, and the snapshot changes with it. Every snapshot made with spread uses the same address, so no number of undos brings Bristol back.

Three ways to fix it:

Memory: every snapshot has a cost

One snapshot of the draft above is only about 100 bytes, so 5 snapshots go unnoticed. It's a different story when the draft carries a parcel photo as a data URL of about 300 KB. structuredClone copies the photo too, in every snapshot: 5 snapshots come to about 1,500 KB, and an uncapped history with 200 edits to about 60 MB.

Exercise: an editor with undo and redo

The exercise uses the same pattern for text. createEditor(maxHistory) returns an object with five methods. Its state is a single string, text, and a JavaScript string can't be changed in place, so the string itself is already a safe snapshot. Nothing needs copying.

With createEditor(3), the starter prints 10 lines: an empty string, Hello, World, 3, true, Hello, (with a space at the end), 1, true, Hello, World, then after an undo and type('!!'): Hello, !! and 0. Also graded: createEditor(2) typed a, b, c keeps only 2 snapshots.

⚠️ Why does undo or redo miss?

TL;DR: Memento keeps a snapshot of the state before each change so it can be brought back. Its three roles: the originator (form, with save and restore), the memento (the snapshot, changed by nobody), and the caretaker (history, which keeps the undo and redo stacks without reading inside them). Undo moves the current state to redo and restores the top snapshot; a new edit empties redo. { ...draft } only copies the top fields, so address is shared and undoing the city keeps Bath; structuredClone copies everything, JSON breaks Date. Every snapshot costs memory: cap it with MAX_HISTORY, drop the old with shift(), and for a big state keep only the change (Command). In the exercise: snapshot text before type, undo and redo return true or false, and historySize() returns { undo, redo }.

⚡ A snapshot before the change

Write:

function edit(field, change) {
  history.undo.push(form.save()) // save BEFORE the change
  if (history.undo.length > MAX_HISTORY) history.undo.shift() // drop the oldest
  history.redo.length = 0 // a new edit cancels redo
  change(form.draft)
}

Meaning: Memento keeps a snapshot of an object's state before it changes, so it can be brought back. Its three roles: the originator (form, which makes and restores snapshots), the memento (the snapshot), and the caretaker (history, which keeps the history without changing what's inside).

⚡ A new edit empties redo

Meaning: Undo moves the current draft onto the redo stack, then restores the top snapshot from the undo stack. A new edit after an undo starts a new branch, so the redo stack is emptied.

⚡ A shallow copy changes too

Guess first: snapshots are made with { ...this.draft }. The admin changes d.address.city to Bath, then presses undo. Which city shows?

Still Bath. { ...draft } only copies the top fields, so the snapshot and the draft hold the same address object.

Meaning: Use structuredClone for a full copy. Every snapshot costs memory, so cap the history with MAX_HISTORY.

What you will learn