-
-
Save MrRedu/9d07fd639449d21772e493b53fde5858 to your computer and use it in GitHub Desktop.
Custom React hook for double-click confirmation for critical actions
This file contains hidden or 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 { useCallback, useEffect, useRef, useState } from "react"; | |
/** | |
* Custom React hook for double-click confirmation for critical actions. | |
* | |
* @param action - The action to be executed on the second click. | |
* @param timeout - Time in milliseconds to reset the unlocked state. | |
* @returns The current unlocked state and the trigger function. | |
*/ | |
const useConfirmation = (action: () => void, timeout: number = 5000) => { | |
const [isUnlocked, setIsUnlocked] = useState<boolean>(false); | |
// Using useRef to persist the timerId without causing re-renders | |
const timerId = useRef<ReturnType<typeof setTimeout>>(); | |
const triggerSafeClick = useCallback(() => { | |
if (isUnlocked) { | |
action(); | |
setIsUnlocked(false); | |
if (timerId.current) { | |
clearTimeout(timerId.current); | |
} | |
} else { | |
setIsUnlocked(true); | |
timerId.current = setTimeout(() => { | |
setIsUnlocked(false); | |
}, timeout); | |
} | |
}, [isUnlocked, action, timeout]); | |
useEffect(() => { | |
return () => { | |
if (timerId.current) { | |
clearTimeout(timerId.current); | |
} | |
}; | |
}, []); | |
return { isUnlocked, triggerSafeClick }; | |
}; | |
export default useConfirmation; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment