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

227
Views
Different function gets passed to useEffect on every render? - ReactJS useEffect

I was going through useEffect from reactjs docs and I've found this statement here

Experienced JavaScript developers might notice that the function passed to useEffect is going to be different on every render.

We are passing a function to useEffect and this function is said to be different for each render. useEffect has access to state and props since it's inside the function component and when either of these changes, we can see that change in the function of useEffect(because of closure) right? This is not clear, because in the next line the doc states

This is intentional. In fact, this is what lets us read the count value from inside the effect without worrying about it getting stale.

To counter this, assume we have a function

function foo(n) {
    bar = () => {
        setTimeout(() => console.log({n}), 50);
        return n;
    }
    setTimeout(() => {n = 10}, 0);
    setTimeout(() => {n = 20}, 100);
    setTimeout(() => {n = 30}, 150);
    return bar;
}

baz = foo(1);
baz(); //prints 10
setTimeout(baz, 300); //prints 30

It seems that when the closure value(n) is changed, we can see that change in the setTimeout's callback (and this callback isn't changed over time). So, how can the closured value(state/props) in useEffect's function become stale as mentioned in docs?

Am I missing something here? I think it's more of a JS question compared to React, so I took a JS example.

about 4 years ago · Juan Pablo Isaza
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!