0

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.

chaukhoa97
  • 35
  • 5
  • Have you tried adding `temp` to the list of dependencies? – alextrastero Sep 07 '21 at 10:40
  • What i mean is it works well with `temp` in the dependency list, but when I omit the `temp`, the function doesn't behave as I expect – chaukhoa97 Sep 07 '21 at 10:44
  • That's because `temp` should live in dependencies: "The array of dependencies is not passed as arguments to the effect function. Conceptually, though, that’s what they represent" – alextrastero Sep 07 '21 at 10:46
  • Also, maybe in this case you don't need to use `useCallback` – alextrastero Sep 07 '21 at 10:47
  • Well I'm learning by a tutorial course, and it shows good example for `useCallback` there. Maybe because I only show the main codes which I have the problem so it may have confused you. Yeah I know that the `temp` should always be in the dependency, but I want to know what are the diffrerencies between 2 ways of declaring that leads to different behaviours of the `useCallback` hook. – chaukhoa97 Sep 07 '21 at 11:09
  • when you trigger a `setState` all variables inside render get redeclared (unless you use useRef) a method declared under useCallback will not be redeclared unless a dependency changes – alextrastero Sep 07 '21 at 13:15

0 Answers0