I'm new to React & learning to using useCallback
. Here's my problem:
In the code, I check if the temp
is true. If yes then the num
will be increased by 1 whenever I press a button (which I have already pointed to the callbackButtonHandler
). Because my dependency array is an empty array, even after 2 seconds when the temp
is set to false by setTemp
, my button still increase the num
by 1 because callbackButtonHandler
is not re-evaluated by React, so the temp
variable in the callbackButtonHandler
won't be changed either. It behaves as I expected so far.
const [temp, setTemp] = useState(true);
setTimeout(() => setTemp(false), 2000);
const [num, setNum] = useState(0);
const callbackButtonHandler = useCallback(() => {
if (temp) {
setNum((prevNum) => prevNum + 1);
}
}, []);
But when I change how I declare temp:
// const [temp, setTemp] = useState(true);
// setTimeout(() => setTemp(false), 2000);
let temp = true;
setTimeout(() => (temp = false), 2000);
...
The button is not working anymore after 2 seconds. I can't explain to myself about this case. I think it is related to Javascript Closures but I'm not sure.