Cache your React event listeners to improve performance.

The Fix

If your function does not depend on your component (no this contexts), you can define it outside of the component. All instances of your component will use the same function reference, since the function is identical in all cases.

The Fix (Advanced)

Author’s Note: I wrote the following examples off the top of my head as a way to repeatedly reference the same function in memory. These examples are meant to make comprehension of references easy. While I would recommend reading this section for the purpose of comprehending references, I would also suggest following it up with the comments section of this article. A few readers have generously contributed better implementations which take into account cache invalidation and React’s built-in memory management.

Conclusion

If you liked this article, feel free to give it a clap or two. It’s quick, it’s easy, and it’s free! If you have any questions or relevant great advice, please leave them in the comments below.

Senior front end engineer / charlesstover.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store