Memento

Term side of the Card.
Topic: Behavioral Patterns
Unit title: Memento
Categories: Design pattern
Explanation side of the Card

Explanation: The design pattern that stores an object's state at a specific point in time and allows it to be restored later. It encapsulates the object's state in a memento object, enabling undo/redo functionality in systems.

Example

Wrongjs
const snapshots = [];
snapshots.push(editor.state);
editor.state.text = 'new';
Rightjs
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 structuredClone or 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.

Analytics cookiesWe'd like to use analytics cookies to see which pages are useful. They're set only if you accept. Privacy Policy