Skip to content

Instantly share code, notes, and snippets.

@freddi301
Last active October 11, 2019 09:52
Show Gist options
  • Select an option

  • Save freddi301/fa601a05d3cd8daa42ab66e69b0ac636 to your computer and use it in GitHub Desktop.

Select an option

Save freddi301/fa601a05d3cd8daa42ab66e69b0ac636 to your computer and use it in GitHub Desktop.
Unduoable state react hook #react #hook
function useUndoState<T>(initial: T) {
const [index, setIndex] = useState(0);
const [history, setHistory] = useState([initial]);
const state = history[index];
const setState = useCallback(
(update: (s: T) => T) => {
const updated = history.slice(0, index + 1);
updated.push(update(state));
setHistory(updated);
setIndex(index + 1);
},
[index, state]
);
const undo = useCallback(() => {
if (index > 0) {
setIndex(index - 1);
}
}, [index]);
const redo = useCallback(() => {
if (index < history.length - 2) {
setIndex(index + 1);
}
}, [index, history]);
return [state, setState, undo, redo] as const;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment