Home > Software design >  Why does running a callback from useEffect print the wrong value
Why does running a callback from useEffect print the wrong value

Time:07-28

I'm trying to understand this weird behavior:

  const [counter, setCounter] = useState<number>(1);
  useEffect(() => {
    setCounter(2);

    setTimeout(function () {
      console.log('counter = ', counter); // => counter = 1
    }, 1000);
  }, []);

CodePudding user response:

Your effect will be called when your component is first mounted, cause you're passing empty array of deps ... where your counter variable is 1

setCounter function is an async function, react-native ui will push that call into the stack of function-calls that's supposed to be called in order, but the the first function call pushed into that stack of calls is your console.log, with a copy of the value of counter variable which is 1

If you want to print the updated value of counter, put counter to the list of deps like:

const [counter, setCounter] = useState<number>(1);
useEffect(() => {
  setCounter(2);
}, []);
useEffect(() => {
  setTimeout(function () {
    console.log('counter = ', counter); // => counter = 1
  }, 1000);
}, [counter]);

CodePudding user response:

What is worth mentioning, you are using counter state value inside useEffect. This is targeted by ESLint with default settings. Your useEffect depends on that state and it should be added to dependency array.[ESLint error][1]

This correct usage of useEffect would cause useTimeout to run 2 times. On initial render and after rerender. [1]: https://i.stack.imgur.com/yiLJi.png

  • Related