Skip to content

Instantly share code, notes, and snippets.

@mjackson
Last active October 16, 2021 11:05
Show Gist options
  • Save mjackson/58262a8989408cf2130a0dbf91aa8e0b to your computer and use it in GitHub Desktop.
Save mjackson/58262a8989408cf2130a0dbf91aa8e0b to your computer and use it in GitHub Desktop.
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