Skip to content

useStateHistory ​

Hook that manages state with history functionality

utilities
test coverage
Last changed: 15 days ago

Installation ​

Library
CLI
Manual
typescript
import { useStateHistory } from '@siberiacancode/reactuse';

Usage ​

typescript
const { value, history, index, set, back, forward, reset, undo, redo, canUndo, canRedo } = useStateHistory(0);

Demo ​

Api ​

Parameters

NameTypeDefaultNote
initialValueValue-- The initial value to start the history with
capacity?number10- Maximum number of history entries and undo actions to keep

Returns

UseStateHistoryReturn<Value>

Type declaration ​

typescript
interface UseStateHistoryReturn<Value> {
  /** True if a redo operation can be performed */
  canRedo: boolean;
  /** True if an undo operation can be performed */
  canUndo: boolean;
  /** All history values */
  history: Value[];
  /** Current index in history */
  index: number;
  /** Current value */
  value: Value;
  /** Go back specified number of steps in history (default: 1) */
  back: (steps?: number) => void;
  /** Go forward specified number of steps in history (default: 1) */
  forward: (steps?: number) => void;
  /** Redo the last change */
  redo: () => void;
  /** Reset history to initial state */
  reset: () => void;
  /** Set a new value */
  set: (value: Value) => void;
  /** Undo the last change */
  undo: () => void;
}

export type StateHistoryAction<Value> =
  | { type: 'BACK'; payload: { steps: number } }
  | { type: 'FORWARD'; payload: { steps: number } }
  | { type: 'REDO' }
  | { type: 'RESET'; payload: { initialValue: Value; capacity: number } }
  | { type: 'SET'; payload: { value: Value; capacity: number } }
  | { type: 'UNDO' };

export interface StateHistory<Value> {
  currentIndex: number;
  history: Value[];
  redoStack: Value[][];
  undoStack: Value[][];
}

Source ​

Source • Demo

Contributors ​

D
debabin
debabin
K
Khasan
Khasan

Released under the MIT License.