I am building a Minesweeper game with React and want to perform a different action when a cell is single or double clicked. Currently, the onDoubleClick
functi
you can use a custom hook to handle simple click and double click like this :
function useSimpleAndDoubleClick(actionSimpleClick, actionDoubleClick, delay = 250) {
const [click, setClick] = useState(0);
useEffect(() => {
const timer = setTimeout(() => {
// simple click
if (click === 1) actionSimpleClick();
setClick(0);
}, 300);
// click in a delay < 250 = double click detected
if (click === 2) actionDoubleClick();
return () => {
clearTimeout(timer);
}
}, [click]);
return () => {
setClick(prev => prev + 1);
};
}
then in your component you can use :
const click = useSimpleAndDoubleClick(callbackClick, callbackDoubleClick);