const Counter = () => {
const [count, setCount] = useState(0);
// return <button onClick={setCount(count + 1)}>{count}</button>;
return <button onClick={() => setCount(count + 1)}>{count}</button>;
};
I'm aware that the commented out line causes an infinite loop but I want to know why that's the case. Isn't the setCount
dispatch function invoked only on click?
It's because the expression within a
{}
in JSX is evaluated and then its result is used where that{}
was — in this case, as the value of theonClick
property. SoonClick={setCount(count + 1)}
evaluatessetCount(count + 1)
(calling the function, which will set the state) and then uses the resulting value for theonClick
. Since calling it sets the state, that causes re-rendering, which does it again endlessly.Your other version creates a function when the JSX is evaluated without calling it, which is why it works.