Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

102
Views
Why does running a callback from useEffect print the wrong value

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);
  }, []);
about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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]);
about 4 years ago · Santiago Trujillo Report

0

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

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!