Skip to content

Instantly share code, notes, and snippets.

@mjackson
Created May 22, 2019 16:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mjackson/629bb1645423591fbc21145d6e4a1f21 to your computer and use it in GitHub Desktop.
Save mjackson/629bb1645423591fbc21145d6e4a1f21 to your computer and use it in GitHub Desktop.
function useStateWithHistory(defaultValue) {
const history = useRef([defaultValue])
const [index, setIndex] = useState(0)
function undo() {
setIndex(index > 0 ? index - 1 : index)
}
function redo() {
setIndex(index < history.current.length - 1 ? index + 1 : index)
}
function setValue(newValue) {
history.current.push(newValue)
setIndex(index + 1)
}
return [history.current[index], setValue, undo, redo]
}
// Use it like this:
const [value, setValue, undo, redo] = useStateWithHistory('some value')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment