packages
useUndo

useUndo

Undo & redo state changes

Usage

const Component = () => {
  const [{ past, present, future }, { canRedo, canUndo, redo, reset, set, undo }] = useUndo<number>(0);
 
  return (
    <>
      <div
        style={{
          padding: '1rem',
          marginBottom: '2rem',
          height: 250,
          border: '1px solid black',
          overflow: 'auto',
        }}
      >
        <pre>{JSON.stringify({ past, present, future }, null, 2)}</pre>
      </div>
 
      <div>
        <p>Count: {present}</p>
        <button onClick={() => set(present - 1)} type='button'>
          -1
        </button>
        <button onClick={() => set(present + 1)} type='button'>
          +1
        </button>
      </div>
 
      <div>
        <button disabled={!canUndo} onClick={undo} type='button'>
          undo
        </button>
        <button disabled={!canRedo} onClick={redo} type='button'>
          redo
        </button>
        <button onClick={() => reset(past[0] || 0)} type='button'>
          reset
        </button>
      </div>
    </>
  );
};

Arguments


NameTypeRequired?
valueany

Returns


IndexNameDescriptionType
0futurefuture state(s) after undoany[]
0pastprevious state(s)any[]
0presentcurrent stateany
1canRedoboolean to help understand if redo is availableboolean
1canUndoboolean to help understand if undo is availableboolean
1redosets state to first future state if available() => void
1resetresets state to initials state() => void
1setsets new state and adds to past state() => void
1undosets state to first past state if available() => void