HooksuseHistory

useHistory()

The useHistory() hook provides a robust way to manage state with time-travel capabilities. It allows you to track past states, undo changes, redo reverted changes, and reset the history stack.

Import

typescript
import { useHistory } from 'the-react-hooks';

Usage

Current Value
0
Can Undo: NoCan Redo: No
Component.tsx
import { useHistory } from 'the-react-hooks';

export const Component = () => {
  const { state, set, undo, redo, canUndo, canRedo } = useHistory(0);

  return (
    <div>
      <h1>Count: {state}</h1>
      
      <button onClick={() => set(state + 1)}>Increment</button>
      
      <button onClick={undo} disabled={!canUndo}>
        Undo
      </button>
      
      <button onClick={redo} disabled={!canRedo}>
        Redo
      </button>
    </div>
  );
}

API

Arguments

  • initialPresent T The initial state value.

Returns

Returns an object with the following properties:
  • state T The current present value of the state.
  • set (newPresent: T) => void Function to update the state. This adds the current state to the past and sets the new value.
  • undo () => void Function to revert to the previous state. Moves the current state to the future.
  • redo () => void Function to re-apply a reverted state. Moves the next future state to present.
  • clear (initialPresent: T) => void Function to reset the history stack and set a fresh initial state.
  • canUndo boolean True if there are past states to undo.
  • canRedo boolean True if there are future states to redo.