K.Kröger
K.Kröger

Reputation: 95

How to understand the event handler behavior in react?

I have recently started working with React and today I came across a topic that got me confused.

The behavior of the synthetic event handlers of react irritates me a bit. I have read that the return values of the event are annulled after calling a callback function.

How should I understand this, and when does this happen in my case?

As you can see in the following Image, the counter gets not incremented.

Case1 Image

But it seems that the problem can be solved, as I have illustrated in the following example.

Case2 Image

How exactly do I have to imagine the behavior here ?

Many thanks for the explanation

Upvotes: 2

Views: 109

Answers (1)

matthiasgiger
matthiasgiger

Reputation: 1256

As far as I can see the event handler looks and should work fine. However, the value of counter is initially undefined and undefined + 1 will not result in a valid number. Try setting an initial count:

const [counter, setCounter] = useState(0)

Great illustrations by the way!

Upvotes: 2

Related Questions