Community JavaScript Snippet

useUndoRedo Hook With Bounded History

The custom hook I drop in whenever an editor screen needs cmd+z. Gives you `undo`, `redo`, `set`, and a hard cap on memory so a long session does not balloon the heap.

useUndoRedo Hook With Bounded History

The custom hook I drop in whenever an editor screen needs cmd+z. Gives you `undo`, `redo`, `set`, and a hard cap on memory so a long session does not balloon the heap.

JavaScript
Frontend
3 snippets
react
hooks
undo-redo
utility
sanjayward

By @sanjayward

November 21, 2025

·

Updated May 20, 2026

622 views

12

4.2 (12)

I always extract the reducer out of the hook before I write useState. The shape { past, present, future, limit } is the standard one (Redux undo uses it too) and the three operations only touch arrays, so I can test them in vitest with no DOM at all. The Object.is short-circuit in pushHistory is non-optional: without it, every keystroke that produces the same value still pushes a history entry and a 30-minute typing session blows past 10k frames. The limit slice keeps the past array bounded, which is the difference between a hook that ships and one that crashes on long-running editors.