useHistoryState
A hook to manage state with undo and redo history.
Overview
useHistoryState works like useState, but it remembers past values. It exposes undo and redo functions, making it perfect for complex forms, editors, or creative tools.
Demo
API Reference
function useHistoryState<T>(initialPresent: T)Returns
Returns an object with:
state: The current value.set(value): Updates the state and pushes to history.undo(): Reverts to previous state.redo(): Moves to future state (if available).canUndo: Boolean.canRedo: Boolean.history: Object containing{ past, present, future }.
Usage Example
import { useHistoryState } from 'react-hooks-ts'
function Editor() {
const { state, set, undo, redo, canUndo } = useHistoryState('')
return (
<div>
<input value={state} onChange={e => set(e.target.value)} />
<button onClick={undo} disabled={!canUndo}>Undo</button>
<button onClick={redo}>Redo</button>
</div>
)
}