Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should I bind methods in React component?

I learn React now and noticed that a lot of people bind their methods in constructor.

Like this:

class MyComponent extends React.Component {
  constructor() {
    super();
    this.myMethod = this.myMethod.bind(this);
  }

  render() {
    <button onClick={this.myMethod}>Click me</button>
  }

  myMethod() {
    // do something
  }
}

But I got used to writing something like this:

render() {
    <button onClick={this.myMethod.bind(this)}>Click me</button>
}

And I was told by a couple of people that using the second method is a bad experience.

So could you tell me the differences between first and second methods? Any pros and cons? or performance issues?

like image 374
Dils Matchanov Avatar asked Jan 27 '23 11:01

Dils Matchanov


1 Answers

You are right and what others told you is also right.

You are encouraged to do binding in constructor because constructor gets called only once per component so if you do binding in constructor it creates a new object/function only once in Webpack bundle.js file hence not much impact

You are not encouraged to do binding directly in render because a component renders for several reasons like when you do setState, when your component receives new props so your component will render so many times. So since you are binding directly in render whenever your component renders it will create a new function every time in Webpack bundle.js and your bundle file size will increase and that affects performance when your app contains thousands of components and if you do binding directly in render in every component.

So you are recommended to do binding only in constructor. Hope that clarifies

like image 145
Hemadri Dasari Avatar answered Feb 01 '23 00:02

Hemadri Dasari