useUndoState
function useUndoState<T>(
initial: T | (() => T),
options?: UndoStateOptions,
): readonly [value: T, set: SetUndoState<T>, controls: UndoControls];
type SetUndoState<T> = (value: T | ((previous: T) => T)) => void;
interface UndoStateOptions {
limit?: number; // how many steps can be undone, default 100
}
interface UndoControls {
readonly undo: () => void;
readonly redo: () => void;
readonly canUndo: boolean;
readonly canRedo: boolean;
readonly clearHistory: () => void; // forget the steps, keep the value
}
Works like useState, and remembers earlier values so they can be undone and redone.
- Each
setthat changes the value adds a step to undo. Setting the value it already has adds nothing, and setting a new value after undoing clears the steps to redo. - Up to
limitsteps are kept, dropping the oldest first. A limit of 0 keeps no history. initialandsetaccept functions just likeuseState, so to store a function, wrap it:set(() => myFunction).set,undo,redoandclearHistorykeep their identity, so they are safe in effect dependencies and memoised children.
Live demo
Example
import { useUndoState } from "react-honey-hooks";
function TitleEditor() {
const [title, setTitle, { undo, redo, canUndo, canRedo }] = useUndoState("Untitled");
return (
<>
<input
value={title}
onChange={(event) => {
setTitle(event.target.value);
}}
/>
<button onClick={undo} disabled={!canUndo}>
Undo
</button>
<button onClick={redo} disabled={!canRedo}>
Redo
</button>
</>
);
}