useUndoRedo
The useUndoRedo
hook manages a stack of user actions to enable undo and redo functionality.
Installation
-
Make sure you have
@ridgehkr/useful
installed in your application. If not, you can get started by following the installation instructions. -
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 theactions
stack.undo()
andredo()
are used to pop and push actions onto theactions
stack, respectivelyclearActions()
is used to delete all actions from theactions
stack as well as any preserved actions resulting fromundo()
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:
Property | Type | Description |
---|---|---|
actions | T[] | An array of actions of type T, representing a stack of all actions that can be undone/redone. |
redo | () => void | Push the most recently undone action back onto the actions stack. |
undo | () => void | Pop the most recent action from the actions stack. |
takeAction | (action: T) => void | Push a new action onto the actions stack. |
clearActions | () => void | Delete all actions from the actions stack as well as any preserved actions resulting from undo() . |