Created
October 28, 2021 13:33
-
-
Save realamirhe/afa63f32050d814ff9bc6f944e06fc48 to your computer and use it in GitHub Desktop.
undo redo react hook which don't cause re-render
This file contains 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, useCallback } from 'react'; | |
export const useUndoRedo = <T>() => { | |
const undoStack = useRef<T[]>([]); | |
const undoPointer = useRef(-1); | |
const add = useCallback((item: T) => { | |
const pointer = ++undoPointer.current; | |
undoStack.current.length = pointer; | |
undoStack.current[pointer] = item; | |
}, []); | |
const reset = useCallback(() => { | |
undoStack.current = []; | |
undoPointer.current = 0; | |
}, []); | |
const undo = useCallback(() => undoStack.current[undoPointer.current--], []); | |
const redo = useCallback(() => undoStack.current[++undoPointer.current], []); | |
const canUndo = undoPointer.current > 0; | |
const canRedo = undoPointer.current !== undoStack.current.length - 1; | |
return { undo, redo, add, reset, canUndo, canRedo }; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment