useStateHistory
The useStateHistory hook keeps a state value together with its history, giving you undo and redo for free. Setting a new value after going back discards the entries that were ahead, just like in a text editor.
Usage
Installation
import { useStateHistory } from "hookstorm";
Parameters
- initialValue — The initial state.
- capacity — (optional) The maximum number of history entries to keep. The oldest entries are dropped first. Default:
100.
Return Values
- state — The current value.
- set(value) — Pushes a new value onto the history. Setting the current value again is ignored.
- undo() — Moves one step back.
- redo() — Moves one step forward.
- go(index) — Jumps to a specific history index (clamped to the valid range).
- reset() — Clears the history back to the initial value.
- canUndo / canRedo — Whether the matching action is available.
- history — All recorded values, oldest first.
- index — The position of the current value in
history.
Example Usage
import { ReactElement } from "react";
import { useStateHistory } from "hookstorm";
export default function Editor(): ReactElement {
const { state, set, undo, redo, canUndo, canRedo } = useStateHistory("");
return (
<div>
<textarea value={state} onChange={(e) => set(e.target.value)} />
<button onClick={undo} disabled={!canUndo}>Undo</button>
<button onClick={redo} disabled={!canRedo}>Redo</button>
</div>
);
}
Notes
- Every
setcall creates a history entry. For fast-changing input, combine it withuseDebouncedCallbackso a single burst of typing becomes one entry. resetrestores the value from the first render; later changes toinitialValueare ignored.