Module: use-history-state
Table of contents
Functions
Functions
useHistoryState
▸ useHistoryState<T
>(initialState_?
): [T
, (newState
: T
) => void
, Object
]
A custom React hook to manage state with history, allowing undo, redo, and reset operations.
Type parameters
Name | Description |
---|---|
T | The type of the state. |
Parameters
Name | Type | Description |
---|---|---|
initialState_? | T | The initial state value. |
Returns
[T
, (newState
: T
) => void
, Object
]
- Returns the current state, a function to update the state, and an object with functions and properties for managing the state history.
The returned object contains:
undo
: A function to revert the state to the previous state.redo
: A function to advance the state to the next state, if available.reset
: A function to reset the state to the initial state.flush
: A function to reset the history, keeping the current state as the only entry.hasPast
: A boolean indicating if there is a previous state in the history.hasFuture
: A boolean indicating if there is a next state in the history.isPresent
: A boolean indicating if the current state is the latest state.isPast
: A boolean indicating if the current state is not the latest state.initialState
: A boolean indicating if the current state is the initial state.historySize
: The total number of states in the history.pointerPosition
: The current position in the history.canReset
: A boolean indicating if the state can be reset to the initial state.modifiedSinceFlush
: A boolean indicating if the state has been modified since the last flush.
Example
const [state, setState, history] = useHistoryState({ count: 0 });
// Update state
setState({ count: state.count + 1 });
// Undo the last state change
history.undo();
// Redo the undone state change
history.redo();
// Reset state to the initial value
history.reset();
// Flush the history, keeping the current state as the only entry
history.flush();
// Check if there are past states
console.log(history.hasPast); // true or false
// Check if there are future states
console.log(history.hasFuture); // true or false
Defined in
react/dist/esm/use-history-state/index.js:54