1.2.3 • Published 5 months ago

react-useundoredostate-hook v1.2.3

Weekly downloads
-
License
MIT
Repository
github
Last release
5 months ago

React useUndoableState Hook

A lightweight module to store historical state and allow undo/redo, including multiple steps backward or forward.

Installation

npm install --save react-useundoredostate-hook

The following packages are peer dependencies and must be installed for this package to work.

react
lodash

Usage Example

Here's a code sandbox for how this hook is used: https://codesandbox.io/s/use-undoable-state-2spts

import React from "react";
import useUndoRedoState from "react-useundoredostate-hook";

export default function Document() {
  const {
    state: doc,
    setState: setDoc,
    resetState: resetDoc,
    index: docStateIndex,
    lastIndex: docStateLastIndex,
    goBack: undoDoc,
    goForward: redoDoc,
  } = useUndoRedoState(
    { text: "The quick brown fox jumps over the lazy dog" }, // initial value
    500 // debounce timeout before states gets updated (optional - defaults to 500)
  );

  const canUndo = docStateIndex > 0;
  const canRedo = docStateIndex < docStateLastIndex;

  return ...
}

Concept

As with useState, useUndoRedoState accepts only 1 argument, the initial value. Behind the scenes, the hook uses two main variables to determine state - index (number) and states (array). states stores the historical values of the state while index determines current state by indicating the current position in the array. states is only written to after a debounced period of debouncePeriod (passed as second param of hook, defaults to 500).

You may navigate through historical states by using the goBack and goForward functions emitted by the hook. However, if you make a call to setState and index is not at the end of the states array, all states after index is erased and index will go back to the end of the states array.

The following table attempts to provide a more detailed explanation of the object returned by the hook:

PropTypeUsageDescription
stateT: anyCurrent state, initialised with argument passed
setState(value: T) => voidsetState(value)Sets state to value. All values after current index is erased
resetState(init: T) => voidresetState(value)Deletes historical states and resets to value
indexnumberThe current index in the states array
lastIndexnumberThe last index in the states array. To determine if can goForward
goBack(steps: number) => voidgoBack(2)Goes back the number of steps passed
goForward(steps: number) => voidgoForward(3)Goes forward the number of steps passed

Thanks to original author

1.2.3

5 months ago

1.2.2

5 months ago

1.2.1

5 months ago

1.2.0

5 months ago

1.1.0

5 months ago