useHistoryState
A hook that manages state and its change history.
Each state change is recorded in history, and you can navigate the history backward (back) or forward (forward). You can also jump to a specific point in history (go) or replace the current state (replaceState).
The maximum number of history entries to store can be limited with a capacity parameter.
Code
Interface
typescript
interface UseHistoryStateReturn<T> {
state: T; // current state value
canForward: boolean; // whether forward navigation is possible
canBack: boolean; // whether backward navigation is possible
setState: (newState: T | ((prevState: T) => T)) => void;
// adds the state to history and updates to the new state
replaceState: (newState: T | ((prevState: T) => T)) => void;
// replaces the current state in history
back: () => void; // navigates to the previous state in history
forward: () => void; // navigates to the next state in history
go: (index: number) => void; // navigates to the state at a specific index in history
}
typescript
function useHistoryState<T>(
initialValue: T | (() => T),
capacity?: number): UseHistoryStateReturn<T>;
Parameters
| Name | Type | Description |
|---|---|---|
initialValue | T | (() => T) | Initial state value or a function that returns the initial value |
capacity | number | Maximum number of history entries to store |
Returns
| Name | Type | Description |
|---|---|---|
state | T | Current state value |
canForward | boolean | Whether forward navigation is possible |
canBack | boolean | Whether backward navigation is possible |
setState | (newState: T | ((prevState: T) => T)) => void | Adds a new entry to history and updates the state |
replaceState | (newState: T | ((prevState: T) => T)) => void | Replaces the current history entry |
back | () => void | Navigates to the previous state in history |
forward | () => void | Navigates to the next state in history |
go | (index: number) => void | Navigates to the state at the specified index in history |
Usage
typescript
import { useHistoryState } from '@modern-kit/react'
const Example = () => {
const {
state,
canBack,
canForward,
setState,
replaceState,
back,
forward,
go
} = useHistoryState(0, 5);
return (
<div>
<p>{state}</p>
<button onClick={() => setState(state + 1)}>+1 (new history)</button>
<button onClick={() => replaceState(state + 10)}>+10 (replace history)</button>
<button onClick={back}>← Back</button>
<button onClick={forward}>Forward →</button>
<button onClick={() => go(0)}>Go to first</button>
<button onClick={() => go(-1)}>Go to last</button>
</div>
)
}
Example
Current value: 0
Back unavailable | Forward unavailable