GitHub
Open Github

UseHistory

Stop losing state changes. useHistory remembers every update so users can undo mistakes, redo actions, and navigate their full edit history.

Installation

pnpm add @hookraft/usehistory

Usage

import { useHistory } from "@hookraft/usehistory"
const { state, set, undo, redo, canUndo, canRedo } = useHistory("", {
  limit: 50,
  onUndo: (state) => console.log("Undid to:", state),
  onRedo: (state) => console.log("Redid to:", state),
  onChange: (state) => console.log("Changed to:", state),
})

Full Example

function TextEditor() {
  const { state, set, undo, redo, canUndo, canRedo, clear, history, jump } = useHistory("", {
    limit: 100,
    onUndo: (value) => console.log("Undid to:", value),
    onChange: () => console.log("Changed!"),
  })

  return (
    <div>
      <textarea
        value={state}
        onChange={(e) => set(e.target.value)}
        placeholder="Start typing..."
      />

      <div>
        <button onClick={undo} disabled={!canUndo}>Undo</button>
        <button onClick={redo} disabled={!canRedo}>Redo</button>
        <button onClick={clear}>Clear</button>
      </div>

      {/* History timeline — click any entry to jump to it */}
      {history.length > 0 && (
        <ul>
          {history.map((entry, index) => (
            <li key={index}>
              <button onClick={() => jump(index)}>
                {entry || "(empty)"}
              </button>
            </li>
          ))}
        </ul>
      )}
    </div>
  )
}

Options

PropTypeDefault
limit
number
100
onUndo
(state: T) => void
-
onRedo
(state: T) => void
-
onChange
(state: T) => void
-

Returns

PropTypeDefault
state
T
-
set(value)
(value: T | ((prev: T) => T)) => void
-
undo()
() => void
-
redo()
() => void
-
canUndo
boolean
-
canRedo
boolean
-
history
T[]
-
future
T[]
-
jump(index)
(index: number) => void
-
clear()
() => void
-