Last active
October 16, 2021 11:05
-
-
Save mjackson/58262a8989408cf2130a0dbf91aa8e0b to your computer and use it in GitHub Desktop.
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 { useRef, useState } from 'react' | |
function useUndo([state, setState]) { | |
const history = useRef([state]) | |
const [index, setIndex] = useState(0) | |
function undo() { | |
setIndex(Math.max(index - 1, 0)) | |
} | |
function redo() { | |
setIndex(Math.min(index + 1, history.current.length - 1)) | |
} | |
function newSetState(nextState) { | |
const nextIndex = index + 1 | |
history.current = history.current.slice(0, nextIndex) | |
history.current[nextIndex] = nextState | |
setIndex(nextIndex) | |
setState(nextState) | |
} | |
return [history.current[index], newSetState, undo, redo] | |
} | |
// Use it like this: | |
function App() { | |
const [message, setMessage, undo, redo] = useUndo(useState('')) | |
// ... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment