useUndoRedo

Custom hook to add undo and redo capabilities to any stateful logic.


✅ Features

  • Undo, redo, reset
  • Full history tracking
  • Easy integration

📦 Usage

1const { state, set, undo, redo, canUndo, canRedo } = useUndoRedo(0)
2
3set(5)
4undo()
5redo()

📋 Source Code

This is the full implementation of useUndoRedo

1import { useCallback, useState } from 'react'
2
3export function useUndoRedo<T>(initialValue: T) {
4  const [history, setHistory] = useState<T[]>([initialValue])
5  const [index, setIndex] = useState(0)
6
7  const value = history[index]
8
9  const set = (val: T) => {
10    const newHistory = history.slice(0, index + 1)
11    setHistory([...newHistory, val])
12    setIndex(newHistory.length)
13  }
14
15  const undo = useCallback(() => {
16    if (index > 0) setIndex(i => i - 1)
17  }, [index])
18
19  const redo = useCallback(() => {
20    if (index < history.length - 1) setIndex(i => i + 1)
21  }, [index, history])
22
23  return { value, set, undo, redo, canUndo: index > 0, canRedo: index < history.length - 1 }
24}
25