Memento
Example
const snapshots = [];
snapshots.push(editor.state);
editor.state.text = 'new';const snapshots = [];
snapshots.push(structuredClone(editor.state));
editor.state.text = 'new';
editor.state = snapshots.pop();A memento must be a copy; storing the live reference means later edits also change the saved snapshot.
Common mistakes
- Saving a reference to state, so later edits also change the saved snapshot.
- Keeping every snapshot of a large document forever and running out of memory.
Key points
- Snapshots are copies, made with
structuredCloneor a spread of immutable data, never live references. - The number of stored snapshots is capped so history doesn't grow without limit.
- Only the originating object reads a memento's contents; other code just stores and returns it.
Interview questions
Memento vs Command for undo: which should I use?
Memento stores full snapshots and is simple but uses more memory. Command stores reversible actions and is lighter but needs a correct undo for every action.
Can I use Memento with immutable state?
Yes, and it gets cheaper. With immutable updates, each old state object is already a snapshot, so history is just an array of references.
What are real examples of the Memento pattern?
Undo in editors, saving game progress, form drafts and rolling back a failed multi-step change.