I'm doing a simple exercise in React of creating a counter using useState. When pressing the button, the counter should be displayed in Html adding +1 for each click. When executing the code it tells me that there is some kind of loop that is executed before I can click on the button. I don't understand why this happens.
import {useState } from 'react';
function Contador() {
const [contador, setContador] = useState(0);
return (
<>
<h1>Contador</h1>
<h1>{contador}</h1>
<button onClick={setContador(contador+1)} >Contar +1</button>
</>
);
}
export default Contador;
What is happening is that when rendering React it is running
setContador
, over and over again. That is, the way you currently have your code executes the codeonClick
from the render and not when you press the button.To correct the error, you must modify the code of the button so that it executes the
setContador
when pressed.The code should be like: