Skip to content

Instantly share code, notes, and snippets.

@KristofferEriksson
Created January 23, 2024 10:11
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save KristofferEriksson/c1f83ad383860733ac6b12b4c4821e19 to your computer and use it in GitHub Desktop.
Save KristofferEriksson/c1f83ad383860733ac6b12b4c4821e19 to your computer and use it in GitHub Desktop.
Custom React hook for double-click confirmation for critical actions
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