React.memo: I’ve still got a lot to learn

How a small change can increase your app performance

TL;DR: Read the documentation

Photo by Ariana Suárez on Unsplash

I consider myself an “experienced” software engineer but almost every day I realize that learning never stops. My last ohhhh moment was about how to optimize re-renders on a React app. I have used React’s memo higher-order component before but never to its full potential. Then I discovered the second argument.

Yes, the second argument.

I don’t know how I have missed this little piece of information for so long but knowing about it can make your app faster when your components are getting heavy and rendering many elements. I’m not gonna lie, I should read more documentation in general.

Now an example.

The above code is a simple React app that renders a counter, a button to increase the counter and a static list. To render the items of the list there is an Item component with a console.log.

Copy and paste the example and run it locally. Change line 31 from ItemMemo to Item. Open DevTools and start clicking the button.

You will see how the rendering message gets printed in the console over and over again. You will notice that even when only changing the counter value, the items on the list get re-rendered on every single click.

This is just an example with 20 elements; imagine 100 or 1000 items re-rendering all the time. Your application will start to slow down, the UI might feel laggy and it will affect how your users interact with and rate it. Now change it back to ItemMemo, click the button and check your DevTools.

Re-rendering no more!

So what is the magic trick? Well there is none, in reality React.memo can accept a function as a second argument. That function has access to the props of the component, both the previous and next values of each prop.

Based on the props we just need to make a comparison and determine if the previous and next props are the same or not. If they are the same return true, otherwise return false.

And that’s it, adding that little change can make big improvements to your React app, and make your users very happy. If you are looking for a fast props comparison NPM package I would recommend react-fast-compare.

P.S. I use console.log in the example above but I would recommend using React Profiler in DevTools for optimizing your React apps.

Lead Software Engineer @ Virtual Academies

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