In the code below I am having an issue.
I was trying to implement doubleClick behaviors and the state hook for the boolean changes to trigger it. The problem is that even though handleDoubleClick function is triggered, setAllowSingleClick is not changing the value to false so anyway the handleClick function is getting triggered.
<div onClick={handleClick} onDoubleClick={handleDoubleClick}>
const CLICK_DELAY_TIME = 200;
const [allowSingleClick, setAllowSingleClick] = useState(true);
let timer = 0;
const handleClick = () => {
timer = setTimeout(() => {
if (allowSingleClick) {
doSMTH1();
}
}, CLICK_DELAY_TIME);
};
const handleDoubleClick = () => {
clearTimeout(timer);
setAllowSingleClick(false);
doSMTH();
};
do not useState() on nested Callbacks. useRef() instead.
useState() itself is just a kind of hook that returns value and setter(asynchronously works).
when setTimeout() callback function is constructed, the value of allowSingleClick variable is fixed in callback function definition (this phenomenon is known as closure).
what useRef() returns itself is object: value evaluated when reference .current property.
example code
import React from "react";
import { useRef } from "react";
function App() {
const CLICK_DELAY_TIME = 200;
const allowSingleClickRef = useRef(true);
const doSMTH1 = () => console.log("!!!");
const doSMTH = () => console.log("???");
let timer = null;
const handleClick = () => {
timer = setTimeout(() => {
if (allowSingleClickRef.current) {
doSMTH1();
}
}, CLICK_DELAY_TIME);
};
const handleDoubleClick = () => {
clearTimeout(timer);
allowSingleClickRef.current = false;
doSMTH();
};
return (
<div
style={{ backgroundColor: "red", width: "100vw", height: "100vh" }}
onClick={handleClick}
onDoubleClick={handleDoubleClick}
/>
);
}
export default App;
More reading: Making setInterval Declarative with React Hooks by Dan Abramov