useUndoState

About

Drop in replacement for useState hook but with undo functionality.

Examples

Basic usage

import "./styles.css";
import { useUndoState } from "rooks";

const App = () => {
  const [value, setValue, undo] = useUndoState(0);

  return (
    <div>
      <span>Current value: {value}</span>
      <br />
      <button onClick={() => setValue(value + 1)}>Increment</button>
      <button onClick={undo}>Undo</button>
    </div>
  );
};

export default App;

Any kind of value

You can pass any kind of value to hook just like React's own useState.

import "./styles.css";
import { useUndoState } from "rooks";

const App = () => {
  const [value, setValue, undo] = useUndoState({ data: 42 });

  return (
    <div>
      <span>Current value: {JSON.stringify(value)}</span>
      <br />
      <button onClick={() => setValue({ data: value.data + 1 })}>
        Increment object data
      </button>
      <button onClick={undo}>Undo</button>
    </div>
  );
};

export default App;

Setter function is still the same

Setter function can also be used with callback just like React's own useState.

import "./styles.css";
import { useUndoState } from "rooks";

const App = () => {
  const [value, setValue, undo] = useUndoState(0);

  return (
    <div>
      <span>Current value: {value}</span>
      <br />
      <button onClick={() => setValue(current => current + 1)}>
        Increment
      </button>
      <button onClick={undo}>Undo</button>
    </div>
  );
};

export default App;

Max undo stack size

To preserve memory you can limit number of steps that will be preserved in undo history.

import "./styles.css";
import { useUndoState } from "rooks";

const App = () => {
  const [value, setValue, undo] = useUndoState(0, { maxSize: 30 });

  return (
    <div>
      <span>Current value: {value}</span>
      <br />
      <button onClick={() => setValue(current => current + 1)}>
        Increment
      </button>
      <button onClick={undo}>Undo</button>
    </div>
  );
};

export default App;

// now when calling undo only last 30 changes to the value will be preserved

Arguments

ArgumentsTypeDescriptionDefault value
initialValuebooleanInitial value of the statefalse
OptionsObjectAn options object for the hook{maxSize: 100}

Note: The second argument is an options object which currently accepts a maxSize which governs the maximum number of previous states to keep track of.

Returned array items

Returned Array itemsTypeDescription
valueAnyCurrent value
setValuefunctionSetter function to update value
undofunctionUndo state value

Join the community!

Join our discord server! You can click the floating discord icon at the bottom right of the screen and chat with us!

Powered by vercel