Duc Dao
Duc Dao

Reputation: 43

React onClick event trigger infinitely on render

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?

Upvotes: 4

Views: 1313

Answers (3)

Utsav Patel
Utsav Patel

Reputation: 2889

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.

Upvotes: 2

Dominic Fernandes
Dominic Fernandes

Reputation: 1

Try this

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

Upvotes: -1

Carlos Saiz Orteu
Carlos Saiz Orteu

Reputation: 1805

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.

Upvotes: 4

Related Questions