React : Is it necessary to bind "this" for an arrow handleclick function?

Hello,

following this code:

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
   
    this.increment = this.increment.bind(this);
   
  }
  
increment() {
  this.setState(state => ({
    count: state.count + 1
  }));
}

  // Change code above this line
  render() {
    return (
      <div>
        <button className='inc' onClick={this.increment}>Increment!</button>
        <h1>Current Count: {this.state.count}</h1>
      </div>
    );
  }
};

If I write increment function like this ( with arrow function ):

increment  =  { () =>
  this.setState(state => ({
    count: state.count + 1
  }));
}

I don’t need to bind it so I can deleted this ? :

this.increment = this.increment.bind(this);

I think the best way to answer this question is to try it :slight_smile: Have you tried using an arrow function for increment and removing the bind in the constructor? Here’s a link you might be interested in:

Should you use arrow functions in React components?

Also, your arrow function version has an issue that will keep your code from running. The opening curly brace isn’t quite in the right spot.

The docs also wouldn’t be a bad place to start.

But I agree, you should be able to answer your own question simply by testing it.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.