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
| Parameter | Type | Default | Description |
|---|---|---|---|
defaultValue | T | (() => T) | — | The initial state value or a function returning the initial value. |
options | { capacity?: number } | { capacity: 10 } | Configuration options for history tracking. |
options.capacity | number | 10 | The maximum number of history states to keep. |
Return Value
useHistory returns a tuple [value, set, { history, pointer, back, forward, go }].
| Property | Type | Description |
|---|---|---|
value | T | The current state value. |
set | (value: T | ((prev: T) => T)) => void | Updates the state and records it in the history. |
history | T[] | The list of recorded state values. |
pointer | number | The index of the current value within the history. |
back | () => void | Moves one step back in the history (undo). |
forward | () => void | Moves one step forward in the history (redo). |
go | (index: number) => void | Jumps to a specific valid index in the history. |
Behavior
- Supports undo/redo navigation through
back,forward, andgo. - New values set after navigating back overwrite the forward (redo) history.
- The history is capped at
capacityentries (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.
defaultValuemay be a value or a lazy initializer function, resolved once on the first render.