State History & Time Travel
useUndoRedoState
About
A hook that provides state management with undo and redo capabilities. It maintains a history of state changes and allows you to navigate through them, making it perfect for features like text editors, drawing apps, or any application where users need to undo/redo their actions.
Examples
Basic counter example
Text editor with function updater
Advanced example with limited history
Arguments
| Argument value | Type | Description | Default | 
|---|---|---|---|
| initialState | T | The initial state value | - | 
| options | Object | Configuration options (optional) | 
Options
| Options value | Type | Description | Default | 
|---|---|---|---|
| maxDepth | Number | Maximum number of states to keep in history. Older states are automatically removed | 100 | 
Returns
Returns an array with three elements:
| Return value | Type | Description | Default | 
|---|---|---|---|
| state | T | The current state value | initialState | 
| setState | Function | Function to update the state (supports both values and functions) | - | 
| controls | Object | An object containing undo/redo methods and state flags | 
Control Methods
| Method | Type | Description | 
|---|---|---|
| undo | Function | Move to the previous state in history | 
| redo | Function | Move to the next state in history | 
| canUndo | Function | Deprecated: Use isUndoPossibleinstead. Returns boolean | 
| canRedo | Function | Deprecated: Use isRedoPossibleinstead. Returns boolean | 
| clearUndoStack | Function | Clear all undo history | 
| clearRedoStack | Function | Clear all redo history | 
| clearAll | Function | Clear both undo and redo history | 
Control Properties
| Property | Type | Description | 
|---|---|---|
| isUndoPossible | Boolean | Whether an undo operation is possible | 
| isRedoPossible | Boolean | Whether a redo operation is possible | 
Notes
- The setStatefunction accepts both direct values and function updaters, just like React'suseState
- When a new state is set, the redo history is automatically cleared
- The hook maintains separate undo and redo stacks internally
- History is limited by the maxDepthoption to prevent memory issues
- The canUndoandcanRedomethods are deprecated in favor of theisUndoPossibleandisRedoPossibleproperties