Last active
November 4, 2020 10:08
-
-
Save jacob-beltran/638dcc9978b498c82d68a19593266999 to your computer and use it in GitHub Desktop.
React Performance: Function Binding Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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