Search code examples
javascriptreactjsevent-handlingarrow-functions

Why do I have to use arrow function in event handler of react?


function ButtonIncrement(){
    const [count,setCount] = useState(0);
    render(){
        <div>
        <h3>
           <button onClick={() => setCount(count+1)}>Increment me for fun</button>
           <p>Count: {count} </p>
        </h3>
        </div>
    }
}

In this onClick button, why does simply putting onClick={setCount(count+1)} not work? I receive an infinite loop, it seems I must use arrow function. I am suspecting it has something to do with the 'this'.


Solution

  • without the arrow function, every button click renders the page again, which sets the state, then it renders again, and sets the state, then it renders again. infinite loop the arrow function recreates that function once when it mounts/updates.

    read more here https://reactjs.org/docs/faq-functions.html