74Implement undo/redo history for a React state editor
mediumAbout 35 minutesCodingreacthooksuseReducerhistory
Problem
Implement useHistory(initialPresent, { limit = 100 } = {}), a hook that works like useState but remembers previous values. It returns:
{ state, set, undo, redo, reset, canUndo, canRedo }set(value)(orset(previous => next)) records a new state. It clears the redo stack.undo()goes back one step;redo()goes forward one step. Both do nothing when there is nothing to undo or redo.reset(value)starts a fresh history withvalueas the present.- Setting a value that is identical (
Object.is) to the present does not add a history entry. - Keep at most
limitpast states; drop the oldest beyond that.
Then use it in an Editor component: a <textarea> with Undo and Redo buttons, and keyboard shortcuts Ctrl/⌘+Z (undo) and Ctrl/⌘+Shift+Z (redo).
Try it yourself
Write your solution, run it, then submit to check it against the tests.
App.jsxReact + DOM
Step-by-step
{ past: [], present, future: [] }. past holds older states (most recent last), future holds states you can redo (next one first).
Unlock the full solution
What's inside
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Tests
Includes 2 code listings, 5 edge cases, 4 follow-up questions.
One-time payment by UPI, card or net banking. Launch price.