Skip to content

Instantly share code, notes, and snippets.

@realamirhe
Created October 28, 2021 13:33
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save realamirhe/afa63f32050d814ff9bc6f944e06fc48 to your computer and use it in GitHub Desktop.
Save realamirhe/afa63f32050d814ff9bc6f944e06fc48 to your computer and use it in GitHub Desktop.
undo redo react hook which don't cause re-render
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