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

348
Views
Why is Javascript closure value apparently captured?
const MyComponent = () => {

  const history = useHistory();

  let [val, setVal] = useState(0);

  useEffect(() => {
      trackPageView();
      history.listen(trackPageView);
  }, []);

  function trackPageView() {
    console.log('hello: ' + val);
    setVal(val + 1);
  }
}

useEffect runs once and registers trackPageView with history.listen. As the history changes, trackPageView is called as expected but val always has the same start value of '0'. (The above code is based on the code in this article.)

In contrast, this code does a similar thing...

var a = 1;

function g(f) {
    return () => f();
}

let func = g(() => console.log('a: ' + a));

func();

a = 2;

func();

...but a's changing value is reflected in the output. https://jsfiddle.net/s3e250da/

So, what accounts for the difference in behaviour?

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!