I'm currently learning the react hooks with an online course.
The instructor passed an anonymous callback function onto the onClick handler
return (
<div className="counter">
<button className="counter-action decrement" onClick={() => decrementScore()}> - </button>
<span className="counter-score">{score}</span>
<button className="counter-action increment" onClick={() => incrementScore()}> + </button>
</div>
);
But I don't understand why the anonymous callback is needed, and why I can't just pass the function by itself.
Following is what I tried and it worked ok without an error.
const Counter = () => {
const [score, setScore] = React.useState(0);
const incrementScore = () => {
setScore(prevScore => prevScore + 1);
}
const decrementScore = () => {
setScore(prevScore => prevScore > 0 ? prevScore - 1 : 0);
}
return (
<div className="counter">
<button className="counter-action decrement" onClick={decrementScore}> - </button>
<span className="counter-score">{score}</span>
<button className="counter-action increment" onClick={incrementScore}> + </button>
</div>
);
}