jacob-beltran
3/3/2017 - 11:34 PM

React Performance: Function Binding Example

React Performance: Function Binding Example

/*
Passing an inline bound function (including ES6 arrow functions)
directly into a prop value is essentially passing a new 
function for each render of the parent component.
*/
render() {
  return (
    <div>
      <a onClick={ () => this.doSomething() }>Bad</a>
      <a onClick={ this.doSomething.bind( this ) }>Bad</a>
    </div>
  );
}


/*
Instead handle function binding in the constructor and pass the
already bound function as the prop value
*/

constructor( props ) {
  this.doSomething = this.doSomething.bind( this );
  //or
  this.doSomething = (...args) => this.doSomething(...args);
}
render() {
  return (
    <div>
      <a onClick={ this.doSomething }>Good</a>
    </div>
  );
}