React Hooks to implement Undo and Redo functionality
undo/redo functionality with React Hooks.
yarn add use-undo
import React from 'react'; import ReactDOM from 'react-dom'; import useUndo from 'use-undo';const App = () => { const [ countState, { set: setCount, reset: resetCount, undo: undoCount, redo: redoCount, canUndo, canRedo, }, ] = useUndo(0); const { present: presentCount } = countState;
return (
); };You clicked {presentCount} times
setCount(presentCount + 1)}> + setCount(presentCount - 1)}> - undo redo resetCount(0)}> reset to 0const rootElement = document.getElementById('root'); ReactDOM.render(, rootElement);
const [state, actions] = useUndo(initialState);
Object
| Key | Type | Description | | ------- | :-----: | ------------------ | | past |
Array| The undo stack. | | present |
Any| The present state. | | future |
Array| The redo stack. |
Object
| Key | Type | Description | | ------- | :--------: | ------------------------------------------------------------------------------------------ | | set |
function| Assign a new value to
present. | | reset |
function| Clear
pastarray and
futurearray. Assign a new value to
present. | | undo |
function| See handling-undo. | | redo |
function| See handling-redo. | | canUndo |
boolean| Check whether
state.undo.lengthis
0. | | canRedo |
boolean| Check whether
state.redo.lengthis
0. |
Refer to Redux Implementing Undo History,
use-undoimplements the same concect with
useReducer.
{ past: Array, present: , future: Array }
It stores all states we need. To operate on this state, there are three functions in
actions(
set,
undoand
redo) that dispatch defined types and necessary value.
MIT © homerchen19