How to avoid unnecessary re-renders with React.memo()
I know there are more optimization techniques, but I think by just avoiding unnecessary re-renders, we can achieve a big improvement in a React app's performance.
In this article, I'll be talking about memoization with React.memo()
.
React.memo()
We've all heard about memoization in React, but do we really understand the concept? Do we really know how to apply the concept in our projects? If your answer is "no", don't worry, I'll explain!
The concept of memoization is pretty simple to understand, just think about the word memorization.
According to Oxford Languages, memorization means:
the process of committing something to memory or learning something by heart.
So there you have it! Just basically think about this:
memoization === memorization
BUT! Before going any further with this topic, I'd like to mention that you should memoize your components wisely because as we all know, everything in excessive amounts could be harmful.
Why do I mention this? Because after understanding the basic concept of memoization and that you can memoize entire components, one might try to memoize every single component in their code, but this is not always the right thing to do.
Because we are memoizing a component, which means that we are basically caching the result of the render, we're trading memory for time. Also, take into consideration that React.memo()
is basically wrapping your component in another component.
Now that we know that we should use React.memo()
wisely, let's jump into some code examples!
Let's look at the sample component below
The above component will receive two arrays of numbers as props and every time it renders will perform the sum operation of all the numbers of both arrays and sum the total of both arrays.
This can cause serious performance issues if we have a big array of numbers.
Now what we want to do is memoize that component, we'll do it like this:
We can rely 100% on the shallow comparison algorithm of React.memo()
, but we can also define our own equality check function!
I wrote the above equality function because, in this example, we are working with arrays. So now with this equality function, we can plug it in as a second argument in React.memo()
!
So there you have it! This was a basic demonstration of how to use React.memo()
to memoize your expensive components and optimize the performance of your React app.
I hope this article helped you at least a little bit in solving performance issues in your app.
Thank you guys for reading and I'll come back with another article next time!
Happy coding!
Subscribe to my newsletter
Read articles from Hyunjin Oh directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Hyunjin Oh
Hyunjin Oh
I'm a frontend engineer and a big fan of delivering high quality code.