I came across this codePen https://codepen.io/enmanuelduran/pen/LgMomz while learning react. I tried to make a few changes and ended up with "Too many re-renders" error.
Instead of
const handleClick = () => setCount(count + 1);
I tried to pass argument to the handleClick function
const handleClick = (x) => setCount(x + count + 1);
and in my return statement I changed
<button onClick={handleClick}>
i added
<button onClick={handleClick(1)}>
when I run it I get
Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
Because here:
You are invoking
handleClickimmediately, not when the button is clicked, hence the function gets called on every render. This then triggers a re-render and you get your 'infinite' loop.Try instead, an anonymous function that in turn calls your
handleClick:Or
If you need to utilise the event object, for example.
For what it's worth, the line that you had previously (
<button onClick={handleClick}>) calls thehandleClickfunction when the button is clicked, but passes the event object as the first argument.