Skip to content

Instantly share code, notes, and snippets.

@neo
Last active November 20, 2016 03:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neo/eec25fbcbbc375f5a7bed2b7a4b71f5a to your computer and use it in GitHub Desktop.
Save neo/eec25fbcbbc375f5a7bed2b7a4b71f5a to your computer and use it in GitHub Desktop.

We used to pass a parent component's method as a prop to the child component like this:

<SomeComponent onClick={this._click.bind(this)} />

But according to the video I watched, it actually creates a reference in memory on that binded function each time React renders the component. And it's so long that we need to type .bind(this) every time we pass a method.

So they introduced a way to pre-bind the method in the constructor like this:

class ParentComponent extends React.component {
  consturctor() {
    super();
    this._click = this._click.bind(this);
  }
  render() {
    return (<SomeComponent onClick={this._click}  />);
  }
}

This way solves two potential issues:

  1. Improve performance by avoiding to create a new reference in memory each time React renders the component (Performance!! YAY!! ✌️)

  2. Less typing for each time passing a method using .bind(this) (Less typing is always better, especially for us developers)

  3. Also, according to the video, it shows all the method that's being pass right in the constructor (apperately they think there's a benefit for that)

So I figured this might be worth sharing. And I am not really sure if this is up to date or even correct, so do give me feedback please!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment