DEV Community

Discussion on: React Beginner Question Thread ⚛

Collapse
 
isaac_jzr profile image
Isaac

What is the best alternative of binding this in the constructor?

Collapse
 
abhirathore2006 profile image
Abhimanyu rathore

i go for following

  1. bind only if you need it in children Component or Event
  2. Re-using same function ? try to use "Call" if that becomes complex then use bind.
Collapse
 
dan_abramov profile image
Dan Abramov

I tend to use class properties:

class Button extends React.Component {
  handleClick = (e) => {
    // no binding
  }
  render() {
    return <button onClick={this.handleClick}>hi</button>;
  }
}

Note they're not standardized yet. But they're so widely used that if the syntax changes or proposal gets dropped, there's definitely going to be an automated migration path (i.e. a codemod).

Collapse
 
shahor profile image
Shahor

Although it looks quite cool I'm really not at ease with class properties because of how they could be confusing, scope wise.

A fat-arrow function is supposed to be bound to the lexical scope in which it is defined and that is very much not the case here, which could lead to some confusions.

I don't know exactly where to stand :D

Thread Thread
 
dan_abramov profile image
Dan Abramov

We’ve been using them in production at Facebook for about a year now, and haven’t seen much confusion in practice.

Collapse
 
matthras profile image
Matthew Mack

As a React newbie this is a game-changer for me. No more headaches with debugging just because I forgot to bind this to functions in the constructor!

Collapse
 
adamthewizard profile image
Adam

Can't believe how old this comment is now! I still check it all the time for syntax lol - It's literally become it's own google search for me! Thanks for the (probably)10+ times this has helped!