0

I am updating a variable in one function and using it in another

 const callNum = () => {
    let number = 5;
    number = number * number;
    setNum(number);
  };

  const callFun = () => {
    console.log("hello");
    callNum();
    setTimeout(() => {
      console.log("callfun", num);
      alert(num);
    },1000);
  };

these are the function above. I am calling it by clicking a button I know setState is asynchronous but as the setState updates shouldn't react re-render. When using console.log it shows the variable is undefined. Please explain why this is happening?

Simran Birla
  • 136
  • 6
  • React wont be able to re-render your app mid-function. It does after the function is done. Instead of doing this via side-effects, use pure functions and pass the new values into it. – Dominik Aug 19 '21 at 05:07
  • Did the console give you a line number where it failed? – DJ Burb Aug 19 '21 at 05:07
  • The `num` variable is not in scope of `callFun`, its purely Javascript and not related to React – Dennis Vash Aug 19 '21 at 05:22
  • React state updates are asynchronously processed, but this doesn't mean you can wait for them to update within a function. In your example, the current `num` state value is closed over in `callFun` callback scope and won't ever be a different value no matter how long the timeout is set for. – Drew Reese Aug 19 '21 at 05:37

0 Answers0