useManualStateHistory

A React Hook that allows you to manage the state history manually.

Demo

Source
{"hash":"ABCDEF","count":0}
/
{"snapshot":{"hash":"ABCDEF","count":0},"timestamp":1747907765548}
5/22/2025, 9:56:05 AM {"hash":"ABCDEF","count":0}

Usage

See API for more details.

Source

Click links below to view source on GitHub.

API

const history = useManualStateHistory(state, options)

State

Any serializable source state value to be record in the history.

Options

export type UseManualStateHistoryOptions<Raw, Serialized = Raw> = {
  /**
   * The capacity of the history records
   *
   * @defaultValue Number.POSITIVE_INFINITY
   */
  capacity?: number
  /**
   * Whether to clone the source state
   *
   * @defaultValue false
   */
  clone?: boolean | CloneFn<Raw>
  /**
   * The throttle options
   *
   * @defaultValue undefined
   */
  throttle?: number | UseThrottledFnOptions
  /**
   * The debounce options
   *
   * @defaultValue undefined
   */
  debounce?: number | UseDebouncedFnOptions
  /**
   * The dump function to serialize the source state
   *
   * @defaultValue (v) => v
   */
  dump?: (v: Raw) => Serialized
  /**
   * The parse function to deserialize the serialized state
   *
   * @defaultValue (v) => v
   */
  parse?: (v: Serialized) => Raw
}

UseThrottledFnOptions is th options of useThrottledFn, see useThrottledFn.

UseDebouncedFnOptions is th options of useDebouncedFn, see useDebouncedFn.

Returns

export type UseRefHistoryRecord<T> = {
  /**
   * The serialized snapshot
   */
  snapshot: T
  /**
   * The timestamp
   */
  timestamp: number
}

export type UseManualStateHistoryReturns<Raw, Serialized> = {
  /**
   * The source state
   */
  source: Raw
  /**
   * The history records
   */
  history: UseRefHistoryRecord<Serialized>[]
  /**
   * The last history record
   */
  last: UseRefHistoryRecord<Serialized>
  /**
   * The undo stack
   */
  undoStack: UseRefHistoryRecord<Serialized>[]
  /**
   * The redo stack
   */
  redoStack: UseRefHistoryRecord<Serialized>[]
  /**
   * Whether can undo or redo
   */
  canUndo: boolean
  /**
   * Whether can redo or undo
   */
  canRedo: boolean
  /**
   * Undo the last change
   */
  undo(): void
  /**
   * Redo the last change
   */
  redo(): void
  /**
   * Clear all history records
   */
  clear(): void
  /**
   * Commit the current source state to history
   */
  commit(): void
}