Memento: saving and going back to a state
- Lesson 26 of 32
- 11 min
- Intermediate
- 13 steps
An editor keeps only its current state, so Ctrl+Z has nowhere to go back to. You will ask the editor itself for a snapshot of its state, keep it in a history without opening it, restore it and compare it with Command's undo.
- Snapshots in the history
- —
- request
- response
- failed request
Step 1 of 13
Problem
You type and there is no way back
You have an editor with two private fields: the text and the cursor position. You type «Hello» and then « world»: the editor holds «Hello world» with the cursor at 11.
Now you press Ctrl+Z. The editor only knows its current state: it never kept what it was before, so it has nowhere to go back to.
What changed
- editor.type("Hello"), editor.type(" world")
Step 2 of 13
Problem
Copying the fields from outside
The quick idea: let the Ctrl+Z code copy text and cursor before each change. But they are private, and TypeScript does not let you read them outside the class.
If you make them public to copy them, the outside code is tied to how the editor is built inside: the day you add the selection or the scroll, every copy that forgets the new field restores half a state.
What changed
- copying private fields from outside
- every new field breaks the copy
Step 3 of 13
Concept
The editor takes the snapshot
The idea of Memento: the object itself makes the copy, because it is the only one that knows what is inside. The editor (the originator) hands out a snapshot of its state, the memento.
Another object, the caretaker (here, the undo history), keeps those snapshots without looking inside. So nobody changes it later, the snapshot is read-only: Readonly in the type.
What changed
- Snapshot, the memento
- history, the caretaker
Step 4 of 13
Technique
Two methods on the editor
save() builds an object with text and cursor and freezes it with Object.freeze, so nobody changes it while it waits in the history. restore(s) does the reverse: it copies the snapshot's values into its fields.
The fields stay private. If you add the selection tomorrow, you add it to Snapshot, save() and restore(): the whole change stays inside the editor, and the outside code never notices.
What changed
- save(): Snapshot
- restore(s: Snapshot)
Step 5 of 13
Solution
A history that only stacks
Before each change, the interface code runs undo.push(editor.save()). The history is just an array of Snapshot: it does not know what is in a snapshot and does not need to.
After typing «Hello» and « world», the history holds 2 snapshots: the empty editor and «Hello». The editor says «Hello world».
What changed
- undo: Snapshot[]
- push(save()) before each change
Step 6 of 13
Solution
Ctrl+Z: restore the last snapshot
Undo is taking the last snapshot out with pop() and handing it to editor.restore(). The editor is back to «Hello» with the cursor at 5, and the history keeps 1 snapshot.
Notice what you did not need: no code that knows how to delete « world». The snapshot says what it was, not how to undo. For redo, keep a snapshot of the state in another list before restoring.
What changed
- the "Hello" snapshot from the history
- editor back to "Hello", cursor 5
Step 7 of 13
Technique
Nobody opens it
Readonly and Object.freeze stop anyone from changing the snapshot, not from reading it: in this code, anyone can look at snap.text. The original pattern goes further: only the originator understands the memento.
If you need that, keep the snapshot class private in the editor's module and export an opaque type with no visible fields: outside code can keep it and hand it back, and TypeScript will not let it read the snapshot without a cast. That is a type barrier, not a runtime one: to stop reading at runtime too, use JavaScript private fields (#text). Often the convention is enough: the history keeps, never reads.
What changed
- Snapshot opaque outside the editor
Step 8 of 13
Concept
You already use it: Redux undo history
The Redux docs suggest wrapping the state in { past, present, future }. Each new action puts present at the end of past and clears `future`. Undo takes the last entry of past, makes it present and moves the old present to the start of future.
Each entry is the whole state, not an inverse: they are snapshots. It works without extra copies because Redux state is immutable, so keeping a reference already keeps the snapshot.
What changed
- history → past and future
- editor → present
Step 9 of 13
Concept
You already use it: the Back button
With history.pushState(state, "", url) a page stores a state object with the browser history entry. When you press Back, the popstate event hands you a copy of that object and the page shows itself as it was.
Same roles: the page builds the snapshot, the browser keeps it without using it. The object must be serialisable, and browsers may limit its size: for large data, use sessionStorage or localStorage.
What changed
- editor → page
- history → browser history
Step 10 of 13
Trade-off
Two ways to undo
In the Command lesson, each command stores how to undo: insert " world" knows how to remove its 6 characters. With Memento you store what it was: the «Hello» snapshot. Both lead to the same «Hello».
Command needs a correct inverse for every action, but each entry is small. Memento needs no inverses, but each snapshot is a copy of the state. You can combine them: a command that keeps a snapshot before it runs instead of an inverse.
What changed
- insert, a command with undo()
- snapshot (what it was) vs inverse (how to undo)
Step 11 of 13
Trade-off
When not to use it and what it costs
Each snapshot is a full copy. With a 2 MB state and 50 snapshots you keep 100 MB (example values). If the state is huge and each change touches little, store differences or commands with an inverse. And give the history a cap.
It does not work either when the state holds things you cannot copy, like an open connection or a timer. Remember too that a new action wipes what you could redo. Redux recommends wrapping only the part of the state that should be undoable.
What changed
- snapshot cap
- large state: differences or commands
Step 12 of 13
Concept
Four wrong ideas
«Memento means saving to disk»: it means going back to an earlier state; writing the snapshot to a file is optional. «Snapshots are free»: each one takes memory. «Undo is always Memento»: Command with inverses is the other way.
«If it is called Memento, it is the pattern»: the VS Code extension API has a Memento interface (behind globalState and workspaceState) that is a key-value store, not snapshots you restore. The name does not prove the pattern: look at what it does.
Step 13 of 13
Summary
Going back without opening the object
When you need to go back to an earlier state without exposing how an object is built, ask the object for the snapshot: save() creates it, a history keeps it without reading it and restore() applies it.
The price is memory per snapshot and choosing well what goes in it. If the state is huge or cannot be copied, use commands with an inverse or store only the differences.
← → step · R replay · Space pause
You will learn
- See why copying the state from outside breaks encapsulation. (covered)
- Tell apart the three roles: originator, memento and caretaker. (covered)
- Implement undo with `save()` and `restore()`. (covered)
- Recognise the idea in Redux undo history and in `history.pushState`. (covered)
- Choose between snapshots and inverses, and know when it does not pay off. (covered)