UNPKG

state-hooks

Version:

Essential set of React Hooks for convenient state management.

37 lines (36 loc) 1.26 kB
/// <reference types="react" /> /** * Wraps a state hook to add undo/redo functionality. * * @param useStateResult Return value of a state hook. * @param useStateResult.0 Current state. * @param useStateResult.1 State updater function. * @param maxDeltas Maximum amount of state differences to store at once. Should be a positive integer. * @returns State hook result extended with an object containing `undo`, `redo`, `past`, `future` and `jump`. * * @example * function Component() { * const [value, setValue, { undo, redo, past, future }] = useUndoable( * useState(''), * ); * // ... * return ( * <> * <button type="button" onClick={undo} disabled={past.length === 0}> * Undo * </button> * <input value={value} onChange={(event) => setValue(event.target.value)} /> * <button type="button" onClick={redo} disabled={future.length === 0}> * Redo * </button> * </> * ); * } */ export default function useUndoable<T>([value, setValue]: [T, React.Dispatch<React.SetStateAction<T>>], maxDeltas?: number): [T, React.Dispatch<React.SetStateAction<T>>, { undo: () => void; redo: () => void; past: T[]; future: T[]; jump: (delta: number) => void; }];