What It Is
The Memento pattern saves a snapshot of an object's state so it can be restored later — without showing the object's insides to anyone. The object itself makes the snapshot and itself restores from it; the outside world just holds the snapshots.
This is the pattern behind “undo to a saved point”, drafts, and checkpoints.
Example: Editor Snapshots
save() returns a snapshot; restore() takes one back. The mistake in between simply disappears.
{ ...this } copies the object's field values into a new object. That copy matters: if the snapshot were the object itself, every later edit would change the “old state” too. For state that holds nested objects or arrays, use structuredClone(this) — a spread copies only the top level.
Save, break, restore
The snapshot was taken while the text was Hello, world!. After the bad edit the editor prints Hello, wrold! oops, and then restore(saved) brings the exact old text back — the holder of the snapshot never looked inside it.
Output: TypeScript file and captured output
// The memento: a saved snapshot of the state.
type Snapshot = {
readonly text: string
}
class Editor {
text: string = ""
// The spread copies the field values, so later edits never reach it.
save(): Snapshot {
return { ...this }
}
restore(snapshot: Snapshot): void {
this.text = snapshot.text
}
}
const editor = new Editor()
editor.text = "Hello, world!"
const saved = editor.save()
editor.text = "Hello, wrold! oops"
console.log("now: ", editor.text)
editor.restore(saved)
console.log("undo:", editor.text)
When to Use It
Use it for checkpoints and rollback: editor undo, game saves, “restore defaults”, transactional steps that may need reverting.
Skip it when the state is one or two plain values — just keep the old value in a variable. And compare with Command: commands undo step by step, mementos jump back to a saved point.
Pros and Cons
Pros: real rollback without exposing internals; snapshots are simple values that can be kept in an array for multi-level undo; marking their fields readonly keeps holders from editing them.
Cons: snapshots of big state cost memory fast; deciding what belongs in the snapshot (and keeping it complete as the class grows) is easy to get wrong.