Pattern 21/22 · Behavioral

Memento

Capture an object's state into a sealed package you can restore later, without forcing the object to expose its internal fields to whoever holds that package.

Behavioral●●○13 min read8 stepsalso known as: Snapshot, Undo State
undo redosnapshothistoryrollbackimmutablebehavioralmemory

01 — It starts with code that is breaking

Problem

Your editor — a product form in a CMS, an order in the admin panel, an invoice — has 12 fields, two nested arrays (variants[], images[]) and a publishedAt: Date. This sprint's ticket: "what kind of app doesn't have Ctrl+Z". Looks easy: state is an object, undo is a pop() off an array.

You write this.history.push(this). Edit three times, hit undo, nothing changes. push(this) stuffs a pointer into the array: history is now 40 pointers to the same live object, so the "old snapshot" and "current" are one and the same. This isn't a logic bug, it's a mental-model bug — you thought you were saving state, you were saving an address.

The next fix is wrong too, in its own way: history.push({ ...this }). A shallow copy keeps the same reference to variants, so when the user adds a variant, every old snapshot grows with it. Switch to JSON.parse(JSON.stringify(this)) and it looks cleaner but quietly breaks things: Date turns into a string, Map/Set become {}, keys holding undefined vanish, class identity and every method are gone. On a 2MB form, each capture costs another 2MB of allocation plus a parse.

Then comes the "rescue": drop private from every field and add restoreAll(state: any) so undo has an easy time. Encapsulation is gone. From then on any file can write form.price = 0 or form.variants = [], bypassing all the validation you put in setPrice(). You just paid with the safety of the whole class, when undo never needed to read a single field — it only needs to hold on to a package.

The second cost, which almost nobody designs for up front: memory. Autosave every 500ms on a 2MB editor, an SPA tab left open all day without a reload → 120 snapshots/hour → over 200MB/hour. The undo stack is the classic memory leak of long-lived apps, and it bloats because nobody set a cap.

02 — The idea, before touching code

Solution

Memento plays exactly one role: the Originator (the object with state) captures its own state into a separate object, and whoever holds it — the Caretaker, i.e. the undo stack, the autosave queue, the deploy history — can't open it. The Caretaker may store, order, cap and evict them freely; to restore, it has to hand the package back to the Originator via restore(memento).

"Captures its own" and "can't open it" are the whole pattern. Drop the first half and your history aliases the present (the bug in paragraph 2). Drop the second and you're forced to make internals public (the bug in paragraph 4). With both, snapshot() returns a token that's hollow to outsiders, while the Originator can read back every word of it.

In TS, the most practical form doesn't need a ceremonious Memento class: a frozen object, captured by value, produced by the Originator itself. And since every snapshot costs real RAM, budget for it from day one: capture at meaningful moments (before an edit, not on every keystroke), cap the count, and for large documents store a diff instead of the whole thing.

03 — Doing it for real, one code fragment per step

Step by step

1

Name the three roles before writing any code

Originator: the object that owns the state and the only place that knows what the state looks like (FormEditor, Cart, Doc). Memento: the state package, opaque to everyone except the Originator. Caretaker: holds mementos and decides when to go back (UndoManager, autosave, deploy history).

Writing these two interfaces down first heads off the bugs in steps 2 and 4, because they force you to answer: who gets to capture, and who gets to open.

tsroles.ts
// Originator : owns the state, captures it ITSELF, opens it ITSELF
interface Originator<M> {
  snapshot(): M
  restore(m: M): void
}

// Caretaker : holds mementos but does NOT know what's inside
class History<M> {
  private items: M[] = []
  push(m: M) { this.items.push(m) }            // just stores, never reads
  get length() { return this.items.length }
  at(i: number): M { return this.items[i] }    // returns the same M, no decoding
}
Notice that History<M> has no idea what M is. That's not an accident — it's the entire strength of the pattern.
Key pointIf the Caretaker can read the Memento's fields, you don't have a Memento, you have a public object.
2

The "bad smell" version: `history.push(this)`

This code runs, throws nothing, and is completely useless. Run it and see for yourself: undo prints the current value.

tsundo-v0.ts
class FormEditor {
  title = ''
  history: FormEditor[] = []      // what does this array actually hold?

  edit(title: string) {
    this.history.push(this)       // <- pushes a POINTER, not state
    this.title = title
    console.log('edit -> ' + this.title)
  }

  undo() {
    const prev = this.history.pop()
    if (!prev) return console.log('undo -> nothing left')
    this.title = prev.title       // prev === this, so this is the CURRENT title
    console.log('undo -> ' + this.title)
  }
}

const f = new FormEditor()
f.edit('A')
f.edit('B')
f.undo()                          // expected "A"
console
edit -> A
edit -> B
undo -> B
history holds pointers that all point to one object. None of the "snapshots" is old.
Key pointUndo bug #1 in JS: saving a reference. Everything else in this pattern exists to block that one line.
3

Shallow copy, JSON round-trip, structuredClone — each wrong in its own way

Three "quick fixes" everyone tries. Knowing where they break matters more than knowing how to use them, because it decides how you package the snapshot in step 4.

tscopies.ts
const snap = { ...editor }             // shallow: variants is STILL ONE SHARED ARRAY
editor.variants.push({ sku: 'TEE-2' })
console.log(snap.variants.length)      // 2  <- the "old" snapshot grows with the present

const viaJson = JSON.parse(JSON.stringify(editor))
editor.publishedAt = new Date('2026-01-05')
console.log(typeof viaJson.publishedAt) // 'string' - the Date became text
console.log(viaJson.note)               // undefined - key vanished (JSON has no undefined)
console.log(viaJson.variants[0].isMain) // undefined - a class getter isn't an own property

// structuredClone(editor): safer than JSON (keeps Date, Map, cycles) BUT:
//   - throws DataCloneError if state contains functions, DOM nodes, class instances with methods
//   - copies 100% every time: a 3MB doc = 3MB for EVERY undo step
Key point{ ...x } aliases nested data, JSON mangles types, structuredClone is safe but expensive. Choosing how to copy is choosing a cost — don't default.
4

The Originator captures itself, by value

Flip the responsibility: nobody captures the editor's state on its behalf. The Originator exposes exactly one method, snapshot(), and inside it decides what to copy and how deep. Outsiders don't need to know which fields FormState has today, or next month.

The line variants: [...this.state.variants] looks small: it's exactly the line that separates a Memento from the bug in step 2. Capture by value, then package it.

tsform-editor.ts
type FormState = { title: string, price: number, variants: { sku: string }[] }

class FormEditor {
  private state: FormState = { title: '', price: 0, variants: [] }

  edit(patch: Partial<FormState>) {
    this.state = { ...this.state, ...patch }
  }

  /** The Originator captures ITSELF. The Caretaker doesn't know the shape, and doesn't need to. */
  snapshot(): Memento {
    return new Memento({ ...this.state, variants: this.state.variants.map(v => ({ ...v })) })
  }

  /** The ONLY way to open the package. */
  restore(m: Memento) {
    this.state = m.unpack(this)      // only the Originator calls this (see step 5)
  }

  view() { return '"' + this.state.title + '" price=' + this.state.price + ' skus=' + this.state.variants.length }
}
Key pointsnapshot() is part of the Originator's API, not an external utility. It lives in the same file as the state, and it knows how deep the state goes.
5

Encapsulation: the Caretaker can't open the Memento

TypeScript's private exists at compile time and is erased completely at runtime — history[0].state works just fine in production. Use # (JavaScript's own private fields) so the encapsulation is a runtime fact, not a lint suggestion.

No getter for the state. For debugging, offer an accessor that leaks no data (bytes). Whoever needs the real data calls restore() — and restore() belongs to the Originator.

tsmemento.ts
export class Memento {
  readonly #state: FormState
  constructor(state: FormState) { this.#state = state }   // # = private at the JS level

  /** Measuring the cost is fine, reading the contents is not. */
  get bytes() { return JSON.stringify(this.#state).length }

  /**
   * "Unpack" is only valid when the caller is the Originator that created this package.
   * Simple options: the Originator passes a secret token, or unpack is a module-internal friend method.
   */
  unpack(by: FormEditor): FormState { return this.#state }
}

const m = editor.snapshot()
m.title            // TS2339: Property 'title' does not exist on type 'Memento'
;(m as any).state  // undefined: there's no property to dig into
m.bytes            // 118 - enough to tell you how much RAM this snapshot costs
Key pointMemento lets the Originator break encapsulation in a controlled way: one way in, named, with an owner.
6

Caretaker: history + cursor, real undo/redo

Proper undo/redo is an array and a cursor, not push/pop. The cursor sits between snapshots. The most commonly forgotten detail: when you edit again after undoing, the redo branch past the cursor must be thrown away — otherwise history becomes an invisible tree and redo starts taking you to nonsense states.

When wiring into Vue, restore must replace the state object, not patch field by field: patching field by field means any field missing from the patch keeps its old value — a "ghost" of the previous edit, and this kind of bug is brutal to track down because it depends on the order of operations.

tsundo-manager.ts
export class UndoManager<M> {
  private items: M[] = []
  private cursor = -1
  constructor(private limit = 50) {}

  push(m: M) {
    this.items = this.items.slice(0, this.cursor + 1)  // drop the redo branch
    this.items.push(m)
    if (this.items.length > this.limit) this.items.shift()
    this.cursor = this.items.length - 1
  }

  prev(): M | undefined { return this.cursor > 0 ? this.items[--this.cursor] : undefined }
  next(): M | undefined { return this.cursor < this.items.length - 1 ? this.items[++this.cursor] : undefined }
}

// The Caretaker doesn't know what a Memento holds; it just hands the package back to the Originator.
const undo = () => { const m = history.prev(); if (m) editor.restore(m) }
const redo = () => { const m = history.next(); if (m) editor.restore(m) }

// Vue: state is a ref -> assign the whole object, once, and reactivity handles the rest.
const state = ref<FormState>({ title: '', price: 0, variants: [] })
Key pointUndo = move the cursor back, then restore. Redo = move it forward. A new edit = cut the tail. Skip the third part and your history is wrong by day two.
7

Cap the memory: a ring buffer and three ways to cut cost

Snapshots are RAM. Do the multiplication before deciding: a light 2KB form × 200 steps ≈ 400KB, no big deal; a 2MB document × 200 steps ≈ 400MB, the tab dies, and it's the profiler that tells you the truth, not code review.

A count cap is mandatory for long-lived apps. A ring buffer (circular array) is the cheapest version: keep the N newest, the oldest gets pushed out without any splice. The trade-off: users who go back more than N steps lose them — a trade-off you state openly, not one you hide.

tsring.ts
/** Circular array: keeps the N most recent mementos, O(1) push, no array slicing. */
export class Ring<M> {
  private buf: (M | undefined)[]
  private head = 0
  get length() { return this.n }
  private n = 0
  constructor(private size = 5) { this.buf = new Array(size) }

  push(m: M) {
    this.buf[this.head] = m
    this.head = (this.head + 1) % this.size
    this.n = Math.min(this.n + 1, this.size)   // once full, n stays put
  }

  at(back: number): M | undefined {             // at(0) = newest
    if (back >= this.n) return undefined
    return this.buf[(this.head - 1 - back + this.size * 2) % this.size]
  }
}

// Three ways to cut cost, ordered by real-world impact:
// 1. Capture on MEANINGFUL events (before applying a change), not on every keystroke
// 2. Debounce 300-500ms: "T-shirt" -> "Cotton T-shirt" is ONE step, not 7
// 3. Store a diff instead of the whole thing (step 8)
Key pointAn unbounded Memento is a memory leak with a nice UI. A cap of N and a debounce are two features, not two optimizations.
8

Large documents: capture a diff instead of everything

Real editors (Monaco, CodeMirror 6, ProseMirror) do not keep 50 copies of the whole document. They store invertible operations: each step only records "insert 3 characters at position 120", and undo runs the inverse operation. Memory drops from O(steps × docSize) to O(steps × changeSize).

Same idea, smaller scale: snapshot per region. A form with 4 tabs? When the user edits the "Shipping" tab, capture only that tab. Undo on that tab never touches the "Content" tab. It's still a Memento — you just picked the granularity.

tspatch-memento.ts
type Patch = { path: string, from: unknown, to: unknown }

/** "Diff" flavored Memento: the package holds the INVERSE, not the whole world. */
class PatchMemento {
  constructor(private patches: Patch[]) {}
  static capture(patches: Patch[]) { return new PatchMemento(patches.map(p => ({ ...p }))) }
  undoPatches(): Patch[] { return this.patches.map(p => ({ path: p.path, from: p.to, to: p.from })) }
  redoPatches(): Patch[] { return this.patches }
}

const m = PatchMemento.capture([{ path: 'price', from: 250000, to: 199000 }])
apply(editor, m.undoPatches())   // undo:  price 199000 -> 250000
apply(editor, m.redoPatches())   // redo:  price 250000 -> 199000

// Change 1 field in a 2MB doc: a 40-byte patch instead of a 2MB snapshot.
// The price: you have to write apply(), and every operation must be expressible as a from/to patch.
Key pointFull snapshots: simple, easy to test, RAM-hungry. Diffs: cheap, but you have to write apply() yourself and trust it. Choose by state size, not by how cool it looks.

04 — Who talks to whom

Structure

  • OriginatorThe object whose state needs protecting (`FormEditor`). Captures itself with `snapshot()`, opens with `restore(m)`. State is private.
  • MementoAn **immutable** state package, captured by value. To outsiders, it has no readable fields.
  • CaretakerUndo stack / autosave queue / deploy history. Orders, counts, caps and evicts mementos — but never opens them.
  • ClientThe user (Ctrl+Z, an Undo button, "Revert to draft") decides *when* to go back; the Caretaker decides *which one*.
COMMON BUG: history holds pointers, not state

  history[0] --+
  history[1] --+-->  FormEditor { title, price, variants[] }
  history[2] --+         ^ all three "snapshots" change with the present

AFTER: three roles, the memento is a sealed package the Caretaker can't open

  Caretaker (UndoManager)            Originator (FormEditor)
  +--------------------------+       +---------------------------+
  | items: Memento[]         | create| - state      (private)    |
  | cursor: number           |------>| + snapshot(): Memento     |
  | + push(m) / prev() /next |<------| + restore(m)              |
  |   stores, never opens    |restore| + view(): string          |
  +------------+-------------+       +---------------------------+
               | holds sealed tokens, O(1)
               v
     [t1]-[p1]-[t2]-[p2]   immutable, max N (ring buffer)
        ^           ^
     oldest      newest (cursor sits here)

05 — Edit freely, run it right here

Try it: undo/redo with a history capped at 5 snapshots

tsdemo.ts
type FormState = { title: string, price: number }

/** Snapshot captured BY VALUE. Nothing outside can reach in and mutate it. */
class Memento {
  constructor(readonly state: Readonly<FormState>, readonly label: string) {}
}
class FormEditor {
  private state: FormState = { title: '', price: 0 }
  private history: Memento[] = []
  private cursor = -1
  constructor(private max = 5) {}

  get labels() { return this.history.map(m => m.label).join(' | ') }
  view() { return '"' + this.state.title + '" price=' + this.state.price }

  edit(patch: Partial<FormState>, label: string) {
    this.state = { ...this.state, ...patch }
    this.history = this.history.slice(0, this.cursor + 1) // drop the redo branch
    this.history.push(new Memento({ ...this.state }, label))
    if (this.history.length > this.max) this.history.shift() // bounded memory
    this.cursor = this.history.length - 1
    console.log('edit  ' + label + ' -> ' + this.view())
  }

  undo() {
    if (this.cursor <= 0) return console.log('undo  refused (at oldest)')
    this.state = { ...this.history[--this.cursor].state }
    console.log('undo  -> ' + this.view())
  }
  redo() {
    if (this.cursor >= this.history.length - 1) return console.log('redo  refused (at newest)')
    this.state = { ...this.history[++this.cursor].state }
    console.log('redo  -> ' + this.view())
  }
}

const form = new FormEditor(5)
form.edit({ title: 'T-shirt' }, 't1')
form.edit({ price: 250000 }, 'p1')
form.edit({ title: 'Cotton T-shirt' }, 't2')
form.undo()
form.undo()
form.redo()
form.edit({ price: 199000 }, 'p2')
console.log('kept: ' + form.labels)
console
edit  t1 -> "T-shirt" price=0
edit  p1 -> "T-shirt" price=250000
edit  t2 -> "Cotton T-shirt" price=250000
undo  -> "T-shirt" price=250000
undo  -> "T-shirt" price=0
redo  -> "T-shirt" price=250000
edit  p2 -> "T-shirt" price=199000
kept: t1 | p1 | p2

The same code runs on Bun: bun run demo.ts. Its output is checked automatically when the site is built.

06 — Honest about the cost

When to use it, when not to

Use it when

  • Undo/redo for real editors: CMS forms, admin pages, canvases, rich text, price tables — places where users will hit Ctrl+Z and will argue with you if it's off by one step.
  • Rolling back an operation when something downstream fails: snapshot the state before calling the API, restore if the response is not ok, instead of writing hand-rolled "undo the math" code.
  • Drafts/autosave: "Revert to previous draft", saving the version before publishing, keeping the N most recent versions for the user.
  • Config/deploys: a single previousConfig slot is a Memento too. Anywhere there's a "go back to the previous version" is a relative of this pattern.
  • Tests: put an object into a complex state with restore(fixtureMemento) instead of calling 20 methods in order.
  • Multi-step flows (wizards) that allow "Back to previous step" while keeping what was already entered.

Don't use it when

  • Saving a reference instead of a value. Bug #1, and it's silent: no errors, undo just "doesn't take". Get suspicious the moment you see push(this), push(form), or an object pulled from a store and shoved into history.
  • Shallow copies of nested state. { ...state } with variants[] gives you two snapshots sharing one array. If state has any child arrays/objects, either deep-copy deliberately or flatten the state.
  • Uncapped history. An SPA open for 8 hours + 500ms autosave = hundreds of MB. Set N, add a debounce, and measure with m.bytes or the Memory tab. The undo stack of a long-lived app is a memory leak with a UI.
  • A Memento holding things that can't be copied: sockets, DB connections, FileHandle, DOM nodes, callbacks. A snapshot must be plain data; live resources are managed by the Originator, not put in the package.
  • restore() patching some of the fields → leftover old state becomes a "ghost". Restore must replace the whole state, or explicitly list every field. This bug depends on the order of operations, so it's very hard to reproduce.
  • Over-engineering: state is a flat object with a few fields, 50 undo steps? history.push(structuredClone(state)) then pop() and you're done. Don't build three classes + an interface for a 6-input form. Memento earns its keep when the state belongs to a class with invariants (validation in setters) that you don't want to expose.

07 — You have met it already, just not by name

In real code

Vue DevTools — Vuex "Time Travel"

The Vuex tab in Vue DevTools keeps a state snapshot after every mutation; drag the slider, the extension swaps in the matching snapshot and the UI jumps right back to that point in the past. The Caretaker (devtools) holds hundreds of mementos without needing to understand the state's shape — exactly the spirit of the pattern.

ProseMirror / CodeMirror 6 / Monaco

None of these three editors stores N copies of the whole document. The history stack holds invertible steps: invert(step) produces the inverse operation, and undo just runs the step backwards. A diff-style Memento — memory scales with the size of the change, not the size of the document.

Zustand temporal, redux-undo

These two middlewares add undo/redo to a store by keeping an array of state snapshots capped at N and moving a cursor. Reading the source of redux-undo is reading a clean Caretaker, written in TypeScript.

structuredClone() — the capture-by-value primitive

Built into Node 17+ and every modern browser, it keeps Date, Map, Set and cycles. It's the fastest way to a safe snapshot, and also a reminder of the limits: it throws DataCloneError as soon as state contains a function or a DOM node, and it copies everything on every call.

08 — Try it yourself

Exercise

Add undo to a `Cart` (items[], coupon, note). Requirements: keep **at most 5** snapshots, capture only **before** an operation changes state (not on every keystroke), undo via an `undoCart()` function, and when `saveCart()` returns an error, automatically restore the most recent snapshot.

Hints, open them one at a time:

  1. Write snapshot() on Cart, returning a new object that Cart creates itself: items must be a new array, otherwise undo will see later pushes too.
  2. Keep the Caretaker separate: a class holding Memento[] + cursor that only calls cart.restore(m) — no .items, no .coupon.
  3. For "auto-restore when the API fails": capture before mutating, try { await save() } catch { cart.restore(last) }. Don't capture after mutating.

Cart is the Originator: snapshot() returns an immutable memento captured by value, and restore(m) is the only way to open it. CartHistory is the Caretaker: a 5-slot circular buffer, push drops the redo branch, prev() moves the cursor back. The cart save flow: snapshot → mutate → save → on error, restore(prevSnapshot).

tsexercise.ts
type CartState = { items: { sku: string, qty: number }[], coupon: string | null, total: number }

class CartMemento {
  constructor(private readonly data: CartState) {}
  unpack(): CartState { return this.data }        // callable, but no field is "read" from outside
  get size() { return this.data.items.length }
}

class Cart {                                          // Originator
  private state: CartState = { items: [], coupon: null, total: 0 }
  snapshot() {
    return new CartMemento({ ...this.state, items: this.state.items.map(i => ({ ...i })) })
  }
  restore(m: CartMemento) { const d = m.unpack(); this.state = { ...d, items: d.items.map(i => ({ ...i })) } }
  add(sku: string, qty = 1) { this.state.items.push({ sku, qty }) }
  view() { return this.state.items.map(i => i.sku + 'x' + i.qty).join(' ') || '(empty)' }
}

class CartHistory {                                   // Caretaker: never opens a memento
  private buf: CartMemento[] = []
  constructor(private cart: Cart, private max = 5) {}
  checkpoint() {
    this.buf.push(this.cart.snapshot())
    if (this.buf.length > this.max) this.buf.shift()   // ring buffer, RAM has a cap
  }
  get kept() { return this.buf.length }
  undo() { const m = this.buf.pop(); if (m) this.cart.restore(m) }
}

const cart = new Cart()
const history = new CartHistory(cart, 5)
history.checkpoint(); cart.add('TEE-1')
console.log(cart.view())
history.checkpoint(); cart.add('PANTS-2')
console.log(cart.view())
history.undo()
console.log('after undo: ' + cart.view())
console.log('checkpoints kept: ' + history.kept)

09 — Read them in pairs to see the essence

Related patterns

  • CommandTwo ways to do undo: with Command each operation knows its own `undo()`, with Memento you save the whole state. They often go together — a Command holds a memento captured before it runs.
  • PrototypeBoth copy. Prototype copies to **clone** a new object of the same shape; Memento copies to **freeze** state, and the copy must not be changeable.
  • StateWhen a state machine allows going back, the stack of previous states is the Caretaker, and the memento is the package you push onto that stack.
  • ObserverAfter `restore()`, you usually need to emit an event so the UI and caches catch up with the new state — otherwise you have the right data and the wrong screen.