Skip to content
usefy

useHistoryState

State & data

A React hook for undo/redo state history with time-travel

Install

$ npm install @usefy/use-history-state

Quick start

useHistoryState.tsx
import { useHistoryState } from "@usefy/use-history-state";

function Editor() {
  const { state, set, undo, redo, canUndo, canRedo } = useHistoryState(
    initialCanvas,
    { limit: 50 }
  );

  return (
    <div>
      <Canvas data={state} onChange={set} />
      <button onClick={undo} disabled={!canUndo}>
        ⟲ Undo
      </button>
      <button onClick={redo} disabled={!canRedo}>
        ⟳ Redo
      </button>
    </div>
  );
}

API reference

useHistoryState<T>(initialState, options?)

Returns the current state plus a stable set of controls for navigating and mutating the undo/redo timeline.

Parameters

ParameterTypeDefaultDescription
initialStateT | (() => T)Initial state, or a factory returning it (evaluated once on mount)
optionsUseHistoryStateOptions{}Configuration (see below)

Options

OptionTypeDefaultDescription
limitnumberunlimitedMax entries to keep. When exceeded, oldest entries drop off the front. Values < 1 = unlimited

Returns

FieldTypeDescription
stateTThe current (present) state
set(next: T | (prev: T) => T) => voidRecord a new state (value or updater). Discards any redoable "future" entries
undo() => voidStep back one entry. No-op when canUndo is false
redo() => voidStep forward one entry. No-op when canRedo is false
goTo(index: number) => voidJump to an entry (index clamped to valid range)
canUndobooleanWhether there is a previous state
canRedobooleanWhether there is a next state
clear() => voidCollapse the timeline down to just the current state
reset() => voidRestore the initial state and wipe the timeline
historyreadonly T[]The full timeline, oldest first
currentIndexnumberIndex of the current state within history

Updater vs. value: like useState, if T is itself a function type, pass an updater (set(() => myFn)) — a bare function argument is always treated as prev => next.


Go deeper

This page is the quick reference. For every example, prop, and edge case, read the full README — or open Storybook to change props live.

More in state & data