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

339
Vistas
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
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