Skip to content

useHistoryTravel

Undo and redo history for a value.

Undo and redo history for a value.

Import

import { useHistoryTravel } from '@kamod-ch/hooks'

Live demo

Basic demo

Undo and redo history for a value.

Back: 0 · Forward: 0

import { useHistoryTravel } from '@kamod-ch/hooks'

export default function UseHistoryTravelDemo() {
  const history = useHistoryTravel('draft')

  return (
    <div>
      <label>
        Value
        <input value={history.value} onInput={(event) => history.setValue(event.currentTarget.value)} />
      </label>
      <p><strong>Back:</strong> {history.backLength} · <strong>Forward:</strong> {history.forwardLength}</p>
      <div class="demo-actions">
        <button type="button" onClick={history.back} disabled={!history.backLength}>Undo</button>
        <button type="button" onClick={history.forward} disabled={!history.forwardLength}>Redo</button>
        <button type="button" onClick={() => history.reset('draft')}>Reset</button>
      </div>
    </div>
  )
}

API

TypeScript signature
export default function useHistoryTravel<T>(initialValue?: T, maxLength?: number): {
    value: T;
    backLength: number;
    forwardLength: number;
    setValue: (this: unknown, val: T) => void;
    go: (this: unknown, step: number) => void;
    back: (this: unknown) => void;
    forward: (this: unknown) => void;
    reset: (this: unknown, ...args: any[]) => void;
};
/

SSR considerations

This hook is safe to import during SSR. If your effect body touches the DOM, keep that work inside the effect callback.

Browser compatibility

Works in any modern browser supported by Preact.