DEV Community

MD Taseen Khan
MD Taseen Khan

Posted on • Originally published at reactjsexample.com on

An enchanced useState hook which keeps track of the states history, allowing you to undo and redo states

useTimeline

An enchanced useState hook which keeps track of the states history, allowing you to undo and redo states

An enchanced useState hook which keeps track of the states history, allowing you to undo and redo states.


useTimeline is a simple hook based on the useState hook which abstracts operations of undo and redo.

A full example is avaiable on here.

Install

With npm:

npm install @mr96/use-timeline

Enter fullscreen mode Exit fullscreen mode

With yarn:

yarn add @mr96/use-timeline

Enter fullscreen mode Exit fullscreen mode

Quick Start

import { useTimeline } from '@mr96/useTimeline';

export default function App() {
  const {
    // current state
    state,
    // set a new state (same API as setState)
    setState,
    // undo by 1 step
    undo,
    // redo by 1 step
    redo,
    // true if there is an undoable state
    canUndo,
    // true if there is a redoable state
    canRedo,
    ...additionalProps
  } = useTimeline('');

  const onChange = (event: ChangeEvent<HTMLInputElement>) => {
    setState(event.target.value);
  };

  return (
    <button disabled={!canUndo} onClick={() => undo()}>
      Undo
    </button>
    <input type="text" onChange={onChange} value={state} />
    <button disabled={!canRedo} onClick={() => redo()}>
      Redo
    </button>
  )
}
Enter fullscreen mode Exit fullscreen mode

GitHub

View Github

Top comments (0)