How to use React Memo and what memoization actually means
React came out with some new goodies in version 16.6. One of ‘em is memo
. A higher order component that can be used as a performance optimiser.
Memo → memoization?
The memo part in React.memo
is a derivative from memoization. If you don’t have a hardcore computer science background, like me, it may throw you off a little bit. Let’s see what Wikipedia can tell us about memoization:
In computing, memoization or memoisation is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again.
The most important thing we learn from this is that not even Wikipedia knows how to spell memoization.
Second, it tells us that it’s a technique that executes a (pure) function once, saves the result in memory, and if we try to execute that function again with the same arguments as before, it just returns that previously saved result without executing the function again.
And that kinda makes sense, doesn’t it? If the arguments are the same as last time, the outcome will be the same as well. So no need to execute that whole damn piece of code again.
The memoization in React.memo
If we pull that definition in to our React ecosystem, the functions that we were talking about, are our React components. And the arguments that we talked about, are our props.
Why do we need React.memo?
Just for the sake of an example, let’s create a container component that uses setState
every second.
This component sets up a setInterval
in the componentDidMount
that sets a randomly picked name from the names
array as state
. This means that the component gets re-rendered every second because setState
is called every second.
The only problem is that our <View />
component gets re-rendered too, even though the name
prop is hardcoded (I used my own name there, ‘cause I’m a filthy narcissist).
This doesn’t really make sense. Why would we want to re-render a component when the props stay the same? (and thus renders the exact same output)
React.memo to the rescue
memo
is a higher order component provided by React that tells the component to only re-render when the props change through the concept of memoization. So let’s wrap our <View />
in a memo
!
As you can see in this CodeSandbox example, the <View />
only gets rendered once, because the name
prop is hardcoded and doesn’t change.
Let’s replace the hardcoded value with the state value (I’ve omitted some lines):
Because our generateName
function generates a random name from an Array of three, there’s a 33.3% chance that it will poop out the same name as the previous poop.
In the case that our generateName
function generates the same name as before, it will not re-render our <View />
component, because the name
prop stays the same! Memoization, baby!
Questions? Hit me up on https://twitter.com/trekinbami.