useStateHistorystate
useStateHistory
NewSSR SAFEState management with undo, redo, and time-travel capabilities through a chronological history of state snapshots.
$ pnpm dlx shadcn@latest add @byphongphan/use-state-historyRequires
@byphongphan in components.jsonuse-state-history.tsx
Loading preview...
Installation
$ pnpm dlx shadcn@latest add @byphongphan/use-state-historyRequires
@byphongphan in components.jsonUsage
Basic Undo and Redo
Bounded History with Capacity Limit
Features
- Undo & Redo Operations: Navigate backwards and forwards through previous state revisions with
undo()andredo(). - Automatic Timeline Branching: Setting a new state while viewing an older snapshot automatically prunes obsolete future history, preserving consistent timeline integrity.
- Capacity Constraint: Optional
capacityoption prevents memory consumption by dropping the oldest entries once the limit is reached. - Direct Time-Travel:
jump(index)allows jumping directly to any arbitrary snapshot with safe index boundary clamping. - Functional State Updates:
setaccepts either raw values or updater functions(prev) => nextVal, matching standard ReactsetStateergonomics. - Lazy Initial State: Supports factory functions
() => initialStatefor expensive initial state calculations.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
initialState | T | (() => T) | — | The initial value or lazy initializer function. |
options.capacity | number | undefined | — | Maximum number of snapshots to retain. Oldest entries are purged. |
Returns
Returns a UseStateHistoryReturn<T> object:
| Property | Type | Description |
|---|---|---|
state | T | The active state snapshot. |
set | (value: T | ((prev: T) => T)) => void | Pushes a new state snapshot into the timeline. |
undo | () => void | Reverts to the previous snapshot. |
redo | () => void | Advances to the next snapshot. |
canUndo | boolean | Whether backward navigation is possible (pointer > 0). |
canRedo | boolean | Whether forward navigation is possible. |
history | T[] | Chronological array of all retained state snapshots. |
pointer | number | Current zero-based index within the history array. |
jump | (index: number) => void | Directly moves the active pointer to a specific snapshot. |
reset | (newInitialState?: T) => void | Resets the timeline with a new or initial baseline value. |