Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

156
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda