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

153
Views
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 answers
Answer question

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 Report
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!