I am new to using React. I tried to make a simple counter in a functional component, where I use the useState hook to increment the value of the counter by 1 each time I press the +1 button. It turns out that calling setCounter
directly on clicking the raise button leads to an error because "the page re-renders infinitely", while calling it as a callback(i.e. () => setCounter()
) renders the component correctly, without falling into a re-render loop. -infinite rendering
import { useState } from "react"
export const CounterApp = () => {
const [counter, setCounter] = useState(10)
return (
<>
<h1>Counter: {counter}</h1>
<hr />
<button onClick={setCounter(counter + 1)}>+1</button> //Uncaught Error: Too many re-renders.React limits the number of renders to prevent an infinite loop.
<button onClick={ () => setCounter(counter + 1)}>+1</button> //Renderiza correctamente
</>
)
}
I would like to know why this infinite re-rendering happens.
This happens because in the onClick event of your button you are directly executing the setCounter() function, so when your component is rendered, setCounter(counter + 1) is executed immediately, which in turn executes the rendering of the component again at modify your counter and so on infinitely.
On the other hand, in your second button you are handing the declaration of a function to the onClick event without executing it, so it will be executed only when the onClick event of your button is executed.
Greetings.
Recommended reading: https://es.reactjs.org/docs/handling-events.html