Last active
October 11, 2019 09:52
-
-
Save freddi301/fa601a05d3cd8daa42ab66e69b0ac636 to your computer and use it in GitHub Desktop.
Unduoable state react hook #react #hook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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