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

202
Views
React functional components how do they preserve the lexical environment of closures?

The following code, listens for any click and updates and shows a counter. The counter is stored in a state variable. The app listens for clicks and calls the increment function, which updates the counter.

What I don't understand is that

set_counter(counter + 1)

does not work. It updates the counter to 1 and then stops. However

set_counter(counter += 1)

which first assigns to counter directly and then calls the setter (which is a pattern that I am trying to avoid), works as expected.

Why is that? Does React not preserve the variables of the lexical environment where the functions are defined, unless you assign to them?


import React, {useEffect, useState} from 'react';

const Logs = () => {
        let [counter, set_counter] = useState(0);

        // Runs on every click
        const increment = () => {
                set_counter(counter += 1);
        };

        // Runs on first render
        useEffect(() => {
                window.addEventListener('click', increment, true);
                return () => window.removeEventListener('click', increment);
        }, []);

        return <div>{counter}</div>;
};

export default Logs;
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!