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?
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>
)
}