API Reference
useUndoRedo

useUndoRedo

The useUndoRedo hook manages a stack of user actions to enable undo and redo functionality.

Installation

  1. Make sure you have @ridgehkr/useful installed in your application. If not, you can get started by following the installation instructions.

  2. Import useUndoRedo into your component.

import { useUndoRedo } from '@ridgehkr/useful'

Example

This is a basic example where useUndoRedo is used to manage a stack of user actions. The actions are represented by a static string, but in practice could be anything other than null or undefined.

  • takeAction() is used to push a new action onto the actions stack.
  • undo() and redo() are used to pop and push actions onto the actions stack, respectively
  • clearActions() is used to delete all actions from the actions stack as well as any preserved actions resulting from undo()
UserActions.tsx
import { useUndoRedo } from '@ridgehkr/useful'
 
function SearchInput() {
  const { actions, redo, undo, takeAction, clearActions } = useUndoRedo()
 
  return (
    <div>
      <button onClick={undo}>Undo</button>
      <button onClick={redo}>Redo</button>
      <button onClick={() => takeAction('New Action')}>Take Action</button>
      <button onClick={clearActions}>Clear Actions</button>
    </div>
  )
}

API Reference

Hook Signature

function useUndoRedo<T>(): UndoRedoState

Parameters

This hook does not accept any parameters. Its type parameter T represents the type of the actions that will be managed by the hook.

Return Value

useUndoRedo returns a UndoRedoState object with the following properties:

PropertyTypeDescription
actionsT[]An array of actions of type T, representing a stack of all actions that can be undone/redone.
redo() => voidPush the most recently undone action back onto the actions stack.
undo() => voidPop the most recent action from the actions stack.
takeAction(action: T) => voidPush a new action onto the actions stack.
clearActions() => voidDelete all actions from the actions stack as well as any preserved actions resulting from undo().