Direct answer
Make the editor's screen a pure function (the same input always gives the same output, with no side effects) of one immutable document value (a value that is never changed in place; an edit builds a new value), and keep history as three pieces: past (earlier documents), present, and future (documents that were undone and can be redone). Every user action produces a new document that shares every untouched part with the old one, so a history entry costs memory only for what changed. Restoring means moving one entry from past to present and rendering it. Nothing else is restored by hand, so listeners and DOM nodes cannot disagree with the state, because the UI is rebuilt from the state.
To keep memory bounded, do three things: share structure between entries, coalesce bursts (typing, dragging) into one entry, and cap the number of entries. When the document is too big or too irregular to keep as shared immutable data, store inverse operations instead of whole documents.
Data model
| Piece | Holds | Why |
|---|
present | { doc, key, at } | the current document, plus the kind of edit (key, for example type:paragraph-7) and its time, used to decide coalescing |
past | earlier entries, oldest first | undo pops the last one |
future | undone entries, nearest first | redo shifts the first one; any new edit empties it |
limit | maximum length of past | bounds memory |
A document is { paragraphs: [{ id, text }, ...] }. Cursor position and selection belong inside the entry too, so that undo puts the caret back where it was (the demo below keeps only the document, to keep the listing short).
Recording actions without exhausting memory
- Structural sharing. An edit builds a new array but reuses every unchanged paragraph object (
{ ...p } only for the paragraph that changed). Two documents then point at the same objects for everything that did not change (structural sharing: the old and new arrays are different, but 999 of their 1000 slots refer to the very same paragraph objects), and a snapshot entry costs the changed paragraph plus a new array of references.
- Coalescing. Several events that the user perceives as one action become one entry.
commit replaces the present entry when the new edit has the same key and arrives within 500 ms of the previous one. A pause, or a different kind of edit, starts a new entry. The 500 ms window is a product choice to tune, not a standard.
- A cap.
past is cut to the last limit entries, so the oldest edits become unrecoverable by design.
- Inverse operations instead of snapshots.
applyOp returns the new document and the operation that reverses it (insert returns remove, and the reverse). The entry then stores one small operation, and undo applies the inverse. This is the right form when the state cannot be shared cheaply or has side effects outside the document, such as a server call that has to be compensated (cancelled by sending a second, reversing call, because the first cannot be taken back) or a canvas object.
Restoring correctly and efficiently
Correctly: undo moves present into the front of future and takes the last past entry as the new present. redo does the reverse. A new commit clears future, because the redo branch no longer describes a reachable next state. Because the UI renders from present.doc, there is no step that re-attaches listeners or re-creates nodes.
Efficiently: after an undo, the new present.doc shares all unchanged paragraphs with the document on screen. A memoized component (React.memo, which skips re-rendering when its props are the same by reference) therefore re-renders only the paragraph that differs.
Demo
The file history.mjs holds the reducer-style functions (each takes the current history and returns the next one, without modifying the old one), setText (the edit that shares structure) and applyOp. The demo measures memory as the number of distinct paragraph objects reachable from the history, compares against deep-cloned snapshots, checks coalescing, the cap, that redo reverses an undo, the redo discard, the inverse-operation round trip, and counts React renders through an edit and an undo.
js
// history.mjs
// Undo/redo as a reducer over { past, present, future }. Each entry is an immutable document.
export const COALESCE_MS = 500;
export function createHistory(doc, limit = 100) {
return { past: [], present: { doc, key: null, at: 0 }, future: [], limit };
}
// commit: record a new document. Edits with the same key within COALESCE_MS replace the
// present entry instead of pushing a new one, so a burst of typing is one undo step.
export function commit(h, doc, { key = null, at = 0 } = {}) {
const sameBurst = key !== null && h.present.key === key && at - h.present.at <= COALESCE_MS;
const past = sameBurst ? h.past : [...h.past, h.present].slice(-h.limit);
return { ...h, past, present: { doc, key, at }, future: [] }; // a new edit discards the redo branch
}
export function undo(h) {
if (h.past.length === 0) return h;
const present = h.past[h.past.length - 1];
return { ...h, past: h.past.slice(0, -1), present, future: [h.present, ...h.future] };
}
export function redo(h) {
if (h.future.length === 0) return h;
const [present, ...future] = h.future;
return { ...h, past: [...h.past, h.present], present, future };
}
// Document edit that shares every untouched paragraph with the previous document.
export function setText(doc, id, text) {
return { ...doc, paragraphs: doc.paragraphs.map((p) => (p.id === id ? { ...p, text } : p)) };
}
// Inverse-operation form: apply returns the new document and the operation that undoes it.
export function applyOp(doc, op) {
if (op.type === 'insert') {
const paragraphs = [...doc.paragraphs.slice(0, op.index), op.paragraph, ...doc.paragraphs.slice(op.index)];
return [{ ...doc, paragraphs }, { type: 'remove', index: op.index }];
}
if (op.type === 'remove') {
const removed = doc.paragraphs[op.index];
const paragraphs = [...doc.paragraphs.slice(0, op.index), ...doc.paragraphs.slice(op.index + 1)];
return [{ ...doc, paragraphs }, { type: 'insert', index: op.index, paragraph: removed }];
}
throw new Error('unknown op ' + op.type);
}
js
// history_demo.mjs
import { JSDOM } from 'jsdom';
import assert from 'node:assert/strict';
import { createHistory, commit, undo, redo, setText, applyOp } from './history.mjs';
const dom = new JSDOM('<!doctype html><div id="root"></div>', { pretendToBeVisual: true });
Object.assign(globalThis, { window: dom.window, document: dom.window.document, IS_REACT_ACT_ENVIRONMENT: true });
const React = (await import('react')).default;
const { createRoot } = await import('react-dom/client');
const { act } = await import('react');
const h = React.createElement;
const makeDoc = (n) => ({ paragraphs: Array.from({ length: n }, (_, i) => ({ id: i, text: `para ${i}` })) });
const deepClone = (d) => structuredClone(d);
const out = (k, v) => console.log(k.padEnd(52), v);
// 1. Memory: 1000 paragraphs, 200 edits of different paragraphs, no coalescing.
function distinctParagraphObjects(hist) {
const all = new Set();
for (const e of [...hist.past, hist.present, ...hist.future]) for (const p of e.doc.paragraphs) all.add(p);
return all.size;
}
let shared = createHistory(makeDoc(1000), 1000), cloned = createHistory(makeDoc(1000), 1000);
for (let i = 0; i < 200; i++) {
shared = commit(shared, setText(shared.present.doc, i, `edited ${i}`), { key: `p${i}`, at: i * 1000 });
cloned = commit(cloned, setText(deepClone(cloned.present.doc), i, `edited ${i}`), { key: `p${i}`, at: i * 1000 });
}
const sharedCount = distinctParagraphObjects(shared), clonedCount = distinctParagraphObjects(cloned);
out('entries in history (past + present):', shared.past.length + 1);
out('paragraph objects held, structural sharing:', sharedCount);
out('paragraph objects held, deep-cloned snapshots:', clonedCount);
assert.equal(shared.past.length, 200);
assert.equal(sharedCount, 1000 + 200); // 1000 originals + one new object per edit
assert.equal(clonedCount, 201 * 1000); // every snapshot owns its own copy of every paragraph
// 2. Coalescing: 20 keystrokes 100 ms apart are one entry; a pause starts a new one.
let t = createHistory(makeDoc(3));
let text = '';
for (let i = 0; i < 20; i++) { text += 'x'; t = commit(t, setText(t.present.doc, 1, text), { key: 'type:1', at: i * 100 }); }
out('undo steps after 20 keystrokes 100 ms apart:', t.past.length);
assert.equal(t.past.length, 1);
t = commit(t, setText(t.present.doc, 1, text + 'y'), { key: 'type:1', at: 19 * 100 + 600 });
out('undo steps after a 600 ms pause and one more key:', t.past.length);
assert.equal(t.past.length, 2);
assert.equal(undo(undo(t)).present.doc.paragraphs[1].text, 'para 1');
// 3. Cap: limit 50, 200 edits.
let c = createHistory(makeDoc(300), 50);
for (let i = 0; i < 200; i++) c = commit(c, setText(c.present.doc, i, `e${i}`), { key: `p${i}`, at: i * 1000 });
let back = c; let steps = 0;
while (back.past.length) { back = undo(back); steps++; }
out('undo steps available with limit 50:', steps);
out('oldest reachable state: paragraph 149 reads:', back.present.doc.paragraphs[149].text);
assert.equal(steps, 50);
assert.equal(back.present.doc.paragraphs[149].text, 'e149');
assert.equal(back.present.doc.paragraphs[150].text, 'para 150');
// 4. Redo reverses an undo, and a new edit discards the redo branch.
let r = commit(createHistory(makeDoc(2)), setText(makeDoc(2), 0, 'a'), { key: 'k1', at: 0 });
r = undo(r);
assert.equal(r.future.length, 1);
const redone = redo(r); // redo is the reverse move
assert.equal(redone.present.doc.paragraphs[0].text, 'a');
assert.equal(redone.past.length, 1);
assert.equal(redone.future.length, 0);
assert.equal(undo(redone).present, r.present);
r = commit(r, setText(r.present.doc, 1, 'b'), { key: 'k2', at: 5000 });
assert.equal(r.future.length, 0);
assert.equal(redo(r), r);
// 5. Inverse operations round-trip a mixed sequence back to the start.
let doc = makeDoc(5); const start = doc; const inverses = [];
for (const op of [
{ type: 'insert', index: 2, paragraph: { id: 90, text: 'new' } },
{ type: 'remove', index: 0 },
{ type: 'insert', index: 4, paragraph: { id: 91, text: 'tail' } },
{ type: 'remove', index: 1 },
]) { const [next, inv] = applyOp(doc, op); doc = next; inverses.push(inv); }
for (const inv of inverses.reverse()) doc = applyOp(doc, inv)[0];
assert.deepEqual(doc, start);
out('inverse ops restore the original document:', 'yes');
// 6. The screen follows the state: render counts per paragraph through an edit and an undo.
const renders = new Map();
const Para = React.memo(function Para({ p }) {
renders.set(p.id, (renders.get(p.id) ?? 0) + 1);
return h('p', { 'data-id': p.id }, p.text);
});
function Editor({ hist }) {
return h('div', null, hist.present.doc.paragraphs.map((p) => h(Para, { key: p.id, p })));
}
async function renderCounts(label, makeNext) {
renders.clear();
const host = document.getElementById('root'); host.innerHTML = '';
const root = createRoot(host);
let hist = createHistory(makeDoc(50));
await act(async () => root.render(h(Editor, { hist })));
const total = () => [...renders.values()].reduce((a, b) => a + b, 0);
const mount = total();
hist = commit(hist, makeNext(hist.present.doc), { key: 'k', at: 0 });
await act(async () => root.render(h(Editor, { hist })));
const afterEdit = total() - mount;
hist = undo(hist);
await act(async () => root.render(h(Editor, { hist })));
const afterUndo = total() - mount - afterEdit;
out(`${label}: paragraph renders on edit / undo:`, `${afterEdit} / ${afterUndo}`);
out(`${label}: DOM text of paragraph 7 after undo:`, host.querySelector('[data-id="7"]').textContent);
await act(async () => root.unmount());
return [afterEdit, afterUndo];
}
const a = await renderCounts('structural sharing', (d) => setText(d, 7, 'changed'));
const b = await renderCounts('deep-cloned snapshots', (d) => setText(deepClone(d), 7, 'changed'));
assert.deepEqual(a, [1, 1]);
assert.deepEqual(b, [50, 50]);
console.log('all assertions passed');
Output:
text
entries in history (past + present): 201
paragraph objects held, structural sharing: 1200
paragraph objects held, deep-cloned snapshots: 201000
undo steps after 20 keystrokes 100 ms apart: 1
undo steps after a 600 ms pause and one more key: 2
undo steps available with limit 50: 50
oldest reachable state: paragraph 149 reads: e149
inverse ops restore the original document: yes
structural sharing: paragraph renders on edit / undo: 1 / 1
structural sharing: DOM text of paragraph 7 after undo: para 7
deep-cloned snapshots: paragraph renders on edit / undo: 50 / 50
deep-cloned snapshots: DOM text of paragraph 7 after undo: para 7
all assertions passed
Reading the numbers: 1000 paragraphs and 200 edits of different paragraphs give 1000 original objects plus 200 edited ones, 1200, with structural sharing. Deep-cloned snapshots give 201 entries of 1000 paragraphs each, 201,000. The counts are objects, not bytes, but both entries hold the same kind of object. Rendering 50 paragraphs, one edit and one undo each re-render exactly 1 paragraph with sharing, and all 50 with cloned snapshots.
What breaks if a technique is removed
The script below copies history.mjs into a temporary folder with one technique removed (the from text replaced by the to text), runs history_demo.mjs against the copy, and prints the first failing assertion. It exits with status 1 if a mutant still passes. Deep-cloning inside the edit is already compared in the demo itself (the deep-cloned snapshots lines: 50 paragraph renders per edit instead of 1).
js
// mutations.mjs
// Copy history.mjs with one technique removed, run the demo against the copy, and print the first failing assertion.
import { readFileSync, writeFileSync, mkdirSync, copyFileSync, rmSync, symlinkSync } from 'node:fs';
import { spawnSync } from 'node:child_process';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
const src = readFileSync('history.mjs', 'utf8');
const mutants = {
'coalescing': ['const sameBurst = key !== null && h.present.key === key && at - h.present.at <= COALESCE_MS;', 'const sameBurst = false;'],
'redo moving the entry back': ['return { ...h, past: [...h.past, h.present], present, future };', 'return h;'],
'the cap': ['.slice(-h.limit)', ''],
'discarding the redo branch': ['present: { doc, key, at }, future: [] }', 'present: { doc, key, at }, future: h.future }'],
};
let survived = 0;
for (const [name, [from, to]] of Object.entries(mutants)) {
if (!src.includes(from)) throw new Error('mutation target not found: ' + name);
const dir = join(tmpdir(), 'history-mutant-' + process.pid);
rmSync(dir, { recursive: true, force: true }); mkdirSync(dir);
writeFileSync(join(dir, 'history.mjs'), src.replace(from, to));
copyFileSync('history_demo.mjs', join(dir, 'history_demo.mjs'));
symlinkSync(join(process.cwd(), 'node_modules'), join(dir, 'node_modules'));
const r = spawnSync('node', ['history_demo.mjs'], { cwd: dir, encoding: 'utf8' });
const lines = r.stderr.split('\n');
const i = lines.findIndex((l) => /^AssertionError/.test(l));
const detail = i >= 0 ? lines.slice(i + 1).find((l) => /!==|!=/.test(l)) ?? '' : lines.find((l) => /Error/.test(l)) ?? '';
console.log(`without ${name}: exit ${r.status} | ${i >= 0 ? lines[i].replace(/:.*$/, '') : ''} ${detail.trim()}`);
if (r.status === 0) survived++;
rmSync(dir, { recursive: true, force: true });
}
if (survived) { console.log(survived + ' mutant(s) still passed'); process.exit(1); }
Run in the same node:22 container (Node 22.23.3) after the demo, node mutations.mjs prints:
text
without coalescing: exit 1 | AssertionError [ERR_ASSERTION] 20 !== 1
without redo moving the entry back: exit 1 | AssertionError [ERR_ASSERTION] 'para 0' !== 'a'
without the cap: exit 1 | AssertionError [ERR_ASSERTION] 200 !== 50
without discarding the redo branch: exit 1 | AssertionError [ERR_ASSERTION] 1 !== 0
Reading it: each line is actual !== expected for the first failing assertion. Without coalescing, 20 keystrokes leave 20 undo steps where 1 is expected; without the cap, 200 undo steps are available where 50 is expected; without clearing future, the redo list still holds 1 entry after a new edit where 0 is expected; with redo replaced by a function that returns its input, the redone document still reads para 0 where a is expected.
Trade-offs and pitfalls
- Snapshots versus operations. Snapshots with sharing are simple to get right: undo cannot drift, because each entry is a complete document. Inverse operations cost less per entry and suit collaborative or server-backed editing, but a bug in one inverse corrupts every later undo, so test them in round trips like the one in the demo.
- Do not put derived or transient state in the history. Hover state, scroll position and "is the menu open" should not be undoable. Record document content and, optionally, selection.
- Undo must not be recorded as an edit.
undo and redo move entries without calling commit; going through commit would clear future and make redo impossible.
- External resources. Anything not held in the document (uploaded files, canvas bitmaps) needs a reference-counting rule (keep a count of how many history entries mention the resource, and free it when the count reaches 0), or old entries keep it alive.
- Collaborative editing changes the question. Undo should usually reverse the current user's own last change, not the document's last change, which a single linear history cannot do.
Running the code
bash
npm init -y && npm pkg set type=module
npm i react@18.3.1 react-dom@18.3.1 jsdom@25.0.1
node history_demo.mjs # the demo
node mutations.mjs # removes each technique once and shows the failing assertion
Run in a node:22 container (Node 22.23.3). Both files sit in the same directory.