Skip to content

Instantly share code, notes, and snippets.

@quisido
Created September 10, 2018 16:45
Show Gist options
  • Save quisido/39e5b25b9d4cb93aa408670d86084fb2 to your computer and use it in GitHub Desktop.
Save quisido/39e5b25b9d4cb93aa408670d86084fb2 to your computer and use it in GitHub Desktop.
Cache your React event listeners to improve performance.
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