Skip to main content

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

🔗 View source 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

NameTypeDescription
initialValueT | (() => T)Initial state value or a function that returns the initial value
capacitynumberMaximum number of history entries to store

Returns

NameTypeDescription
stateTCurrent state value
canForwardbooleanWhether forward navigation is possible
canBackbooleanWhether backward navigation is possible
setState(newState: T | ((prevState: T) => T)) => voidAdds a new entry to history and updates the state
replaceState(newState: T | ((prevState: T) => T)) => voidReplaces the current history entry
back() => voidNavigates to the previous state in history
forward() => voidNavigates to the next state in history
go(index: number) => voidNavigates 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