Created
March 29, 2022 22:09
-
-
Save nihlton/57c6db57a90c07c884e6f7a0bd2e24e3 to your computer and use it in GitHub Desktop.
state hook, with history methods (set/undo/redo)
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
import { useState } from 'react'; | |
const useHistory = (initialState) => { | |
const [history, setHistory] = useState([initialState]); | |
const [historyPos, setHistoryPos] = useState(0); | |
const canUndo = historyPos; | |
const canRedo = historyPos !== history.length - 1; | |
const value = history[historyPos]; | |
const undo = canUndo ? () => setHistoryPos((p) => p - 1) : null; | |
const redo = canRedo ? () => setHistoryPos((p) => p + 1) : null; | |
const set = (nVal) => { | |
const finalValue = typeof nVal === 'function' ? nVal(value) : nVal; | |
const newHistory = [...history.slice(0, historyPos + 1), finalValue]; | |
setHistory(newHistory); | |
setHistoryPos(newHistory.length - 1); | |
}; | |
return [value, set, undo, redo]; | |
}; | |
export default useHistory; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment