Difference between binding a method and not

I’ve been into a several React projects now, and I’ve notice in one project that every new method is not binded. What is the actual difference (if there’s any)? Why bind if you could do it like the second example?

In the first case, the code has looked like this:

constructor(props) {
  super(props);
  this.state = { myState: false };
  this.clickMe = this.clickMe.bind(this);
}

clickMe() {
  this.setState({ myState: !this.state.myState });
}

The other example looks like this:

constructor(props) {
  super(props);
  this.state = { myState: false };
}

clickMe = () => {
  this.setState({
    myState: !this.state.myState
  });
}

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

In constructure,

this.clickMe = this.clickMe.bind(this);

Using bind method you do explicit this binding to provide context to clickMe method.

ie. React Component Scope here

In short,you taking care to decide what is the invoking context scope (this binding).

But with

clickMe = () => {
  this.setState({
    myState: !this.state.myState
  });
}

Arrow function take care for you do lexical scope binding of the React Component scope within which it is define.No need to use bind

If you dont use arrow function,without bind,your function will not get binded to React Component scope.

Solution 2

Arrow functions are great because they are faster and easier to write. In a small or medium size app there’s not a tangible difference. You can use the arrow functions if you prefer and avoid the binding inside the constructor.

However, someone has decided to look at performance and side effects. So you can check these 2 links:

  1. When Should I User Arrow Functions?

  2. Arrow Functions in Class Properties Might Not Be As Great As We Think

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply