Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React onClick event trigger infinitely on render

Tags:

reactjs

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?

like image 376
Duc Dao Avatar asked Sep 03 '25 10:09

Duc Dao


1 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.

like image 188
Carlos Saiz Orteu Avatar answered Sep 05 '25 01:09

Carlos Saiz Orteu