# Memento

> The Memento design pattern captures and externalizes an object's state, allowing it to be restored later without revealing its implementation details.

## What is the Memento design pattern?

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.

- Topic: Behavioral Patterns
- Type: design pattern

## Example

Wrong:

```js
const snapshots = [];
snapshots.push(editor.state);
editor.state.text = 'new';
```

Right:

```js
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.

## Related cards

- [Command](https://wonderium.dev/engineering/command.md)
- [structuredClone()](https://wonderium.dev/js/structured-clone.md)
- [Deep Copy](https://wonderium.dev/js/deep-copy.md)
- [Encapsulation](https://wonderium.dev/engineering/encapsulation.md)
- [State](https://wonderium.dev/engineering/state.md)

---

- Level: [Engineering](https://wonderium.dev/engineering.md)
- HTML version: https://wonderium.dev/engineering/memento
- Last updated: 2026-11-25
