Skip to content

Instantly share code, notes, and snippets.

@jacob-beltran
Last active November 4, 2020 10:08
Show Gist options
  • Save jacob-beltran/638dcc9978b498c82d68a19593266999 to your computer and use it in GitHub Desktop.
Save jacob-beltran/638dcc9978b498c82d68a19593266999 to your computer and use it in GitHub Desktop.
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>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment