Skip to Content
ohooks

useHistoryState

Manages state with undo/redo history tracking and configurable history capacity.

Loading preview...

The useHistoryState hook manages a state value alongside bounded past and future stacks, providing undo, redo, and clear helpers for reversible user actions.

Installation

pnpm dlx shadcn@latest add https://ohooks.vercel.app/r/useHistoryState.json

Usage

Examples

Text Editor with Undo and Redo

Use canUndo and canRedo to enable or disable toolbar buttons as the user edits state.

Limiting History Capacity

Pass a capacity argument to cap the maximum number of undo snapshots retained in memory.

API Reference

UseHistoryStateReturn

Current state, history stacks, and undo/redo controls returned by the hook.

Property
Specification
state
T
Current present state value
past
array
Array of previous state snapshots
future
array
Array of undone state snapshots available for redo
canUndo
union
Whether there is at least one past state to undo to
canRedo
union
Whether there is at least one future state to redo to
set
function
Updates the present state and pushes the previous state onto past
undo
function
Steps backward to the most recent state in past
redo
function
Steps forward to the next state in future
clear
function
Clears past and future history while keeping the current state
reset
function
Resets state to the initial value (or a new provided value) and clears history