Created
September 10, 2018 16:45
-
-
Save quisido/39e5b25b9d4cb93aa408670d86084fb2 to your computer and use it in GitHub Desktop.
Cache your React event listeners to improve performance.
This file contains hidden or 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
class SomeComponent extends React.PureComponent { | |
// Each instance of SomeComponent has a cache of click handlers | |
// that are unique to it. | |
clickHandlers = {}; | |
// Generate and/or return a click handler, | |
// given a unique identifier. | |
getClickHandler(key) { | |
// If no click handler exists for this unique identifier, create one. | |
if (!Object.prototype.hasOwnProperty.call(this.clickHandlers, key)) { | |
this.clickHandlers[key] = () => alert(key); | |
} | |
return this.clickHandlers[key]; | |
} | |
render() { | |
return ( | |
<ul> | |
{this.props.list.map(listItem => | |
<li key={listItem.text}> | |
<Button onClick={this.getClickHandler(listItem.text)} /> | |
</li> | |
)} | |
</ul> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment