Skip to main content

useHistory

useHistory is a custom React hook to manage state with history tracking, supporting undo/redo functionality.

Usage

import { useHistory } from "hookify-react";

export default function UseHistoryExample() {
const [value, setValue, { history, pointer, back, forward, go }] =
useHistory(0, { capacity: 5 });

return (
<div style={{ textAlign: "center", fontFamily: "Arial, sans-serif" }}>
<h2>useHistory Hook Example</h2>
<p>Current Value: <strong>{value}</strong></p>
<button onClick={() => setValue((prev) => prev + 1)}>Increment</button>
<button onClick={() => setValue((prev) => prev - 1)}>Decrement</button>
<button onClick={() => setValue(0)}>Reset</button>
<hr />
<button onClick={back} disabled={pointer === 0}>Undo</button>
<button onClick={forward} disabled={pointer === history.length - 1}>
Redo
</button>
<button onClick={() => go(0)} disabled={pointer === 0}>Go to Start</button>
<p>History: {JSON.stringify(history)}</p>
<p>Pointer: {pointer}</p>
</div>
);
}

API Reference

Parameters

ParameterTypeDefaultDescription
defaultValueT | (() => T)The initial state value or a function returning the initial value.
options{ capacity?: number }{ capacity: 10 }Configuration options for history tracking.
options.capacitynumber10The maximum number of history states to keep.

Return Value

useHistory returns a tuple [value, set, { history, pointer, back, forward, go }].

PropertyTypeDescription
valueTThe current state value.
set(value: T | ((prev: T) => T)) => voidUpdates the state and records it in the history.
historyT[]The list of recorded state values.
pointernumberThe index of the current value within the history.
back() => voidMoves one step back in the history (undo).
forward() => voidMoves one step forward in the history (redo).
go(index: number) => voidJumps to a specific valid index in the history.

Behavior

  • Supports undo/redo navigation through back, forward, and go.
  • New values set after navigating back overwrite the forward (redo) history.
  • The history is capped at capacity entries (default 10); the oldest entries are dropped once the cap is exceeded.
  • Setting a value identical to the current one does not add a new history entry.
  • defaultValue may be a value or a lazy initializer function, resolved once on the first render.