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

155
Vistas
Reactjs closure issue with event handlers

I'm new to Reactjs and I'm working on one project.

A typical scenario I'm facing is the handling of events, and values storing inside variables:

let counter = 0;

function clickHandler() {
  counter++;
}

For as absurd as it can appear, all the time I use this pattern in reactjs I get counter undefined, the only way I can turn around this is to put the counter inside a state. I tried a PoC in codesandbox and everything works, so I'm getting crazy trying to understand the reason of this weird behaviour.

Then my question: is there any typical react scenario which cause a function/handler to not see its closure correctly?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

A typical way of doing this in react will be to use state. Check the useState hook documentation https://reactjs.org/docs/hooks-state.html

import { useState } from 'react';

const Component = () => {
  const [counter, setCounter] = useState(0)
  
  const incrementCounter = () => setCounter(counter + 1)
  
  return (
    <button onClick={incrementCounter}>Increment</button>
  )
}

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