React: onClick handler is getting called on every render?
I am learning React, and followed this tutorial to create a simple Tic-Tac-Toe game that you can view here in CodePen.
I am confused about how the arrow function works in the onClick
property of the Square component that is being returned inside of the renderSquare
function of the Board component: onClick={() => this.props.onClick(i)}
. And also again similarly the Game component where I have onClick={ (i) => this.handleClick(i)}
. I assumed I could write it without the arrow function (just like onClick={this.handleClick(i)}
) but this breaks the game.
Solution 1:
onClick
expects a function. An arrow function does not have its own this
; the this
value of the enclosing execution context is used.
Arrow function is a replacement for the following
onClick={this.handleClick.bind(this,i)}
It doesn't work when you run it like
onClick={this.handleClick(i)}
because in this case it will call a function and that will pass a return value that will be evaluate everytime render is called. So if you are doing somethings in the onClick function that causes a rerender for instance setState
you app will go in an endless loop. Thus onClick
needs a function and not a value so unless you are returning a function from the onClick
handler you should not directly call it.
Arrow function above performs the role of binding the parameter to the function