Posted

1 minute read

There are two ways you can bind functions in React:

  • one option is inside the constructor of the class component
  • the other is works implicitly by using ES6 arrow functions


class MyComponent extends React.Component {
  constructor(props) {
    super(props)
  }

  handleClick = () => { ... }
}

or


class MyComponent extends React.Component {
  constructor(props) {
    super(props)

    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() { ... }
}

The performance of both implementation is identical since the second implementation is compiled to the first one.

Understanding the .bind() method

Let’s try to understand the .bind() implicit method:

  1. this.handleClick = this.handleClick.bind(this); – First this.handleClick refers to the handleClick() method defined in the class – this refers to MyComponent
  2. this.handleClick = this.handleClick.bind(this); – Second this.handleClick is the same handleClick() method and we call the implicit .bind() method
  3. this.handleClick = this.handleClick.bind(this); – The last this is where we pass the context to .bind() and refers to MyComponent context

This will allow you to move the context of the handleClick to the component and be able to update the state:


<button onClick={this.handleClick}>Click button</button>

<button onClick={() => this.handleClick()}>Click button</button>

Thanks for reading. I hope you learned something interesting about React!
If you found this article useful, please share it with others. Don’t forget to subscribe to get notified for the upcoming articles.