React Hook — useMemo

KY
8 min readJan 7, 2023

Youtube link

I just have some really basic boilerplate code set up for us to test our application

Two pieces of state one is a number which we can control by this over here on the right and the second one is a boolean for dark or light which is toggled by this change theme button on the right of screen then what we do is we have a function which doubles our number so just multiples by two but this function is very slow if I scroll down here you can see

I just have a really long for loop that just loops doing nothing for a really long time to emulate what would happen in a really slow long-running complex function obviously since this function just multiplies by two all this code is doing is making the function really slow and if I change this number for example by clicking this up arrow you’re gonna see it takes about a second half a second for it to actually double the number so you can see this function is quite slow to execute now continuing on word we just have a variable here which is taking this dark boolean and changing if we have a darker theme down here and then lastly over here we just have the output code which changes our number when we update here and also toggles our theme when we click this button so that’s just the basics of our code and you may think this is okay is fine code it’s working great and the slowness is you know not that bad

2:30

but it only is gonna be slow going we update our number but actually that’s incorrect thinking if we click our change theme button you’re gonna notice

We have the same delay I’m going to click it , now you can see it takes about half a second to a second for it to actually change the actual theme and the reason for that is , because one you update state and react .

It’s going to re-render your entire component so it’s going to run this entire function from top to bottom which means that this slow function gets called every single time .

That we render our app component so

  • whether we’re changing the theme
  • whether we’re actually updating the number here
  • whether some other component is causing this component to re-render you’re going to be forcing it to go through that slow function

over and over and over again and this is a really big performance效能 problem when you have these slow functions that don’t really changing that often so react has a built in way to solve this with a hook which is called useMemo so.

useMemo

so we can import this views memo hook just like this and memo here stands for memorization which essentially is the idea of caching a value so you don’t have to recompute重新計算 it every single time .

3:40

So in our example this slowed function

  • takes an input of a number and it’s always going to
  • give us the same output every time we give it the same input

So we can cache that input value number and the output it gives us that way if the number doesn’t change.

We don’t have to recalculate重新運算 our SLO function over and over and over again and the easy way to use this is we just call useMemo.

And we’re going to pass it in a function and this function is going to be the thing that we actually memorize so this is the thing that we’re caching which in our case is going to be this slow function we just want to make sure we return this slow function here get the result from it and then just like all of the other hooks that we talked about like use effect

For example, we’re going to have a list of dependencies here and in our case the dependency of this is going to be our number here our number is the. only thing that changes and when our number changes we need to return the code inside this use memo hook

but if our number doesn’t change we don’t need to return this slow function code ,

4:40

so with that one simple change let’s save and see what happened to our app.

It’s loading over here we can change this to for example 1 and you can see it has a kind of delay change it up again it’s going to have a delay .

When click Change theme you’re going to notice this is instantaneous瞬間 I can click it as much as I want to and that’s because when we go through our code we click Change theme it causes our component to re-render so it calls this function does all this stuff and it gets down to use memo and it says well our number is exactly the same as what it was last time.

5:20

So we’re not gonna recall this slow function here because we already know what the result is it’s the exact精確的 same thing as it was last time so we’re saving ourselves from having to recalculate this number with the slow function and we only are forcing ourselves我們自己 to do this when we actually update this number instead of our input here so we’re essentially本質上 only running this slow code when we have to and

not running it when we don’t actually need to now this seems really nice

5:36

And you may think let me just memo everywhere why not just memorize. Everything like this theme style is here why don’t I memorize that based on this dark boolean variable and the reason you don’t want to memorize. Everything is because it does give you some performance效能 overheads and some memory記憶體 overhead.

For example, this used memo function must be called every single render of your component. So you’re calling an additional function and also it’s saving the value this previous value in some memory variable so you’re forcing your memory to get larger every time you use memo.

Because you have to store an additional variable in memory to store that previous value now this isn’t a huge deal but if you start to do this everywhere in your application especially where you don’t need it it’s going to cause additional memory usage and additional performance problems when just not using it would have been better .

So, I highly recommend you only use memo in this case when you actually need the performance benefits when the function you’re calling is incredibly slow then use memo is grate but there’s also a second use case for used memo and that is something called the referential參考性的 equality平等 .

And if you aren’t really familiar with value versus相對的 reference in JavaScript I have a video on topic I’ll link int the cards in description but essentially what that is saying is when you try to compare相比 two different variables in JavaScript it’s going to compare the reference .

In the case of objects and arrays so for example this theme Styles here is a specific object and if I were to duplicate this theme Styles to right here you would think that theme styles and theme style 2 are equal to each other but in JavaScript they reference two different objects they have the same values in the object but the reference to the object itself is different these two values are not actually equal to each other which in something really important and as you know instead of hooks .

7:26

And react we have this array here all of our dependencies and when our dependencies change it’s going to return our hook so let’s click a quick example.

Where we have a use effect and we want to run this use effect . Every single time that our theme styles here changes , so we’re just gonna have a really simple console.log theme changed and down here inside of our dependencies I’m going to have our theme styles.

let’s get rid of this console down here and of course we need to make sure we import use effect just that and now I just really quickly inspect this page here pull this over go to the console oops , console .

You can see we get our theme changed being printed out and when we change our theme you can see it’s continually printing out theme changed but a problem you’ll notice if I clear this out is when we changed our number it’s also causing this theme change to be run and the reason for that is that referential equality what’s happening is every time we run our function we get a new theme styles object being created and this new theme style object is not the same as the old theme styles even though have the exact same values in the object the reference different places in memory and that’s really important to know so in order to make sure that we only ever run use effect when our theme style object actually gets real we can useMemo .

So what we can do is wrap this a used memo make sure you pass it a function and in here we’re just going to return that object you just indent all this properly and in here for our dependencies we’re just gonna put that dark variable because that’s the only thing that this object depends on .

Now if we were to rerun this you can see a change in our theme causes this to update our theme logs it out but when we change our number you’re gonna notice we don’t actually get anything printed in our console and only when we click change theme and the reason for this is that now we are wrapping this object inside of memorization essentially if our dark variable doesn’t change we don’t read 8 theme styles so we get the exact same reference as we had the previous time we rendered our app so now our use effect is comparing our old theme styles with our new theme styles , but they both reference. the exact same object so these are two big use cases for a use memo the first and most obvious is when you want to make a slow function we wrap it in this use memo so that doesn’t recompute every single time you render your component .

10:15

And only computes when you actually need the value from that function since the inputs actually changed the second use case which is a little bit tricker is this idea of a referential equality whenever you want to make sure the reference of an object or an array is exactly the same as it was the last time you rendered if none of the internal workings changed you’re gonna want to use memo here to make sure that you only update the reference of that object whenever the actual contents of the object change

instead of updating every single time you render .

And that’s all there is to the used memo hook if you enjoyed this video make sure to check out my full react course linked in the description to get a full over view of everything you need to know about react.

Thank you very much for watching and have a good day.

--

--