Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

213
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda