To make it clear, this is not React-specific behavior
; it is a part of how functions work in JavaScript
. Generally, if you refer to a method without ()
after it, such as onClick={this.handleClick}
, you should bind
that method.
If calling bind annoys you, there are two ways you can get around this. If you are using the experimental public class fields syntax
, you can use class fields to correctly bind callbacks.
If you aren’t using class fields syntax, you can use an arrow function in the callback
.
The problem with arrow function syntax
is that a different callback is created each time the button
renders. In most cases, this is fine. However, if this callback is passed as a prop
to lower components, those components might do an extra re-rendering
. We generally recommend binding in the constructor or using the class fields syntax, to avoid this sort of performance problem.
You can read more about this on their documentation here:
https://reactjs.org/docs/handling-events.html