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.