React onClick event trigger infinitely on render

Viewed 586

So i ran into some funny bug with React onClick event. So if I write something like this:

login = () => {
  this.setState({ authed: true })
  alert(this.state.authed)
}
render() {
  return (
    <div>
      <Loginpage />
      <button onClick={this.login}>test</button>
    </div>
  );

it would function normally but if onClick is changed to onClick={this.login()}, this event will be triggered on render and continue infinitely even after changing the code back and re-render this will still go on. I'm just curious why it ends up like that, does anyone knows?

3 Answers

If you use this onClick={this.login()} you are calling the function as soon as it renders and not onClick, that's why your component is infinitelly rendering.

So if you do this:

<button onClick={this.login}>test</button>

You are passing a reference to the function login on click of the button.

But if you do this:

<button onClick={this.login()}>test</button>

Then you are executing the function as soon as this element is rendered.

The login function triggers a state change:

login = () => {
  this.setState({ authed: true })
  alert(this.state.authed)
}

And since state change triggers another render, therefore it goes into the infinite loop.

Had you not called the setState in login, it would not go into the infinite loop.

Only your function will execute without even clicking the button on render.

Try this

<button onClick={()=>this.login}>test</button>
Related