miscellaneous

Undo/redo functionality with React Hooks

Jan 16, 2019
Undo/redo functionality with React Hooks

use-undo

React Hooks to implement Undo and Redo functionality.

View Demo Download Source

Requirement ⚠️

To use useUndo, you have to use at minimum [[email protected]](/cdn-cgi/l/email-protection). React Hooks is currently at RFC stage.

Installation

yarn add use-undo

Usage

Edit 5v9yoz7xn4

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 ( <div> <p>You clicked {presentCount} times</p> <button key="increment" onClick={() => setCount(presentCount + 1)}> + </button> <button key="decrement" onClick={() => setCount(presentCount - 1)}> - </button> <button key="undo" onClick={undoCount} disabled={!canUndo}> undo </button> <button key="redo" onClick={redoCount} disabled={!canRedo}> redo </button> <button key="reset" onClick={() => resetCount(0)}> reset to 0 </button> </div> ); }; const rootElement = document.getElementById('root'); ReactDOM.render(<App />, rootElement);

API

useUndo

const [state, actions] = useUndo(initialState);

state

Type: Object
KeyTypeDescription
pastArrayThe undo stack.
presentAnyThe present state.
futureArrayThe redo stack.

actions

Type: Object
KeyTypeDescription
setfunctionAssign a new value to present.
resetfunctionClear past array and future array. Assign a new value to present.
undofunctionSee handling-undo.
redofunctionSee handling-redo.
canUndobooleanCheck whether state.undo.length is 0.
canRedobooleanCheck whether state.redo.length is 0.

How does it work?

Refer to Redux Implementing Undo History, use-undo implements the same concect with useReducer.
The state structure looks like:

{ past: Array<T>, present: <T>, future: Array<T> }

It stores all states we need. To operate on this state, there are three functions in actions (set, undo and redo) that dispatch defined types and necessary value.

GitHub

Recommended