Learn useMemo In 10 Minutes

Web Dev Simplified
6 Jun 202010:42

Summary

TLDRThis video from Kyle's React hooks series dives into the use of the `useMemo` hook in React. It explains how `useMemo` can improve performance by caching the result of a function, preventing unnecessary re-computations. The video demonstrates how `useMemo` can be used to optimize a slow function that is executed on every render, showing how it can reduce the delay caused by such functions. Additionally, it covers the concept of referential equality in JavaScript and how `useMemo` can be utilized to ensure hooks like `useEffect` only rerun when there's a meaningful change in the referenced objects. The video concludes with a reminder to use `useMemo` judiciously to avoid unnecessary memory and performance overhead.

Takeaways

  • 📚 **UseMemo Introduction**: The video introduces the `useMemo` hook in React, explaining its purpose and when it should be used.
  • 🔁 **Performance Optimization**: `useMemo` is used to optimize performance by memoizing the result of expensive function calls and only recomputing when necessary.
  • ⏱️ **Slow Function Problem**: The script demonstrates a slow function that is re-run on every render, which can be inefficient and cause delays in the user interface.
  • 💡 **Memoization Concept**: `useMemo` is based on the concept of memoization, caching the result of a function so it's not recalculated on every render when the inputs remain the same.
  • 📈 **Dependencies List**: The hook takes a function and a list of dependencies; the function is re-executed only when one of the dependencies changes.
  • 🚀 **Instantaneous Updates**: By using `useMemo`, the video shows how the theme toggle can be updated instantly without waiting for a slow function to execute.
  • 🚧 **Overuse Caution**: The video warns against overusing `useMemo` due to the additional performance and memory overhead it can introduce if not necessary.
  • 🤝 **Referential Equality**: A second use case for `useMemo` is managing referential equality, ensuring objects or arrays are only considered changed when their actual content changes, not just their reference.
  • 🔗 **Effect on useEffect**: `useMemo` can be used to control when effects run by ensuring the reference to an object remains the same unless the dependency changes.
  • 🛠️ **Selective Use of useMemo**: The video advises using `useMemo` selectively, only in cases where there are clear performance benefits or when dealing with referential equality issues.
  • 📝 **Debugging Tips**: The script provides insights into debugging and understanding the reactivity and rendering behavior in React components.

Q & A

  • What is the main topic of the video?

    -The main topic of the video is an explanation of the `useMemo` hook in React and its proper usage.

  • Why is `useMemo` important in React applications?

    -`useMemo` is important because it helps improve performance by memoizing the results of expensive function calls and only recomputing them when one of the dependencies changes.

  • What does the video suggest as a condition for using `useMemo`?

    -The video suggests using `useMemo` when there is a need for performance optimization with slow-running functions or when ensuring referential equality of objects or arrays.

  • Why might one not want to use `useMemo` for every piece of state in a React component?

    -One might not want to use `useMemo` for every piece of state because it introduces additional memory and performance overhead by storing previous values and adding the extra function call on every render.

  • What is the downside of re-rendering a component with a slow function every time the state updates?

    -The downside is that the slow function will be executed on every render, causing unnecessary delays and performance issues, especially when the function does not need to be re-executed for the specific state change.

  • How does `useMemo` help with referential equality in React?

    -`useMemo` helps with referential equality by ensuring that the reference to an object or array remains the same across renders unless one of its dependencies changes, thus preventing unnecessary re-renders.

  • What is the purpose of the 'change theme' button in the example provided in the video?

    -The 'change theme' button is used to toggle between a dark and light theme in the example application, demonstrating how state updates can trigger re-renders and the potential performance impact.

  • How does the video demonstrate the effectiveness of `useMemo`?

    -The video demonstrates the effectiveness of `useMemo` by showing a noticeable performance improvement when toggling the theme without the delay that was present before using `useMemo` to wrap the slow function.

  • What is the role of dependencies in the `useMemo` hook?

    -Dependencies in the `useMemo` hook determine when the memoized function should re-run. If any of the dependencies change, the function will be re-executed; otherwise, the cached result will be used.

  • What is the second use case for `useMemo` discussed in the video?

    -The second use case for `useMemo` discussed in the video is to ensure that the reference of an object or array remains constant across component re-renders unless the actual content of the object changes.

  • What does the video recommend for optimizing React applications?

    -The video recommends using `useMemo` judiciously, only in cases where there are significant performance benefits, such as with slow functions or when dealing with referential equality issues.

Outlines

00:00

🚀 Introduction to useMemo and React Performance

This paragraph introduces the useMemo hook in React and its importance for performance. The speaker explains the use case of useMemo when dealing with slow functions that do not need to be recomputed on every render. They provide an example of a slow function that doubles a number and demonstrate how useMemo can prevent unnecessary re-execution of this function when the input (number) remains the same. The paragraph also discusses the potential performance and memory overhead of using useMemo and advises its use only when necessary.

05:00

📚 Referential Equality and useMemo for Dependencies

The second paragraph delves into the concept of referential equality in JavaScript and how it relates to React's useMemo hook. The speaker illustrates the issue with objects and arrays where even if they have the same values, they are not considered equal if they are different instances. This can lead to unnecessary re-renders if not handled correctly. To address this, useMemo can be used to ensure that a dependency object, like theme styles, is only re-evaluated when its actual content changes, not with every render. The speaker also provides a practical example of using useMemo within a useEffect hook to prevent unwanted side effects from firing.

10:01

🎓 Summary of useMemo Hook Use Cases

In the final paragraph, the speaker summarizes the two primary use cases for the useMemo hook. The first is optimizing performance by preventing the re-computation of slow functions when their inputs have not changed. The second is ensuring referential equality for objects or arrays, so that components only re-render when the actual content of these objects changes, not with every render cycle. The speaker encourages viewers to check out their full React course for a comprehensive understanding of React, and thanks the audience for watching.

Mindmap

Keywords

💡React

React is a popular JavaScript library for building user interfaces, particularly for single-page applications. It is the main focus of the video, as the script discusses various aspects of React development, such as hooks and performance optimization.

💡Hooks

In React, hooks are a feature that allows developers to use state and other React features without writing a class component. The video specifically covers the use of the `useMemo` hook, which is a way to optimize performance by memoizing computations.

💡useMemo

The `useMemo` hook is used in React to optimize performance by memoizing the result of a function. It is a key concept in the video, where the presenter explains how to use `useMemo` to avoid unnecessary recalculations of a slow function within a component's render.

💡Memoization

Memoization is a technique used to speed up programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again. In the context of the video, memoization is employed with `useMemo` to prevent the re-computation of a slow function unless necessary.

💡State

State in React refers to a component's data that, when changed, can trigger a re-render of the component. The video script mentions state in the context of a number and a boolean for theme toggling, which are used to demonstrate the effects of state changes on component re-renders.

💡Re-render

Re-rendering in React occurs when a component's state changes, causing the component to update its output. The video discusses the performance implications of re-renders, particularly when they are caused by slow functions that are re-executed on every render.

💡Performance Optimization

Performance optimization is the process of improving the efficiency and speed of an application. The video's main theme revolves around using React's `useMemo` hook for performance optimization by reducing unnecessary computations and re-renders.

💡Dependencies

In the context of React hooks, dependencies are a list of values that determine when a hook should re-execute its function. The video explains how the dependencies list in `useMemo` ensures that the memoized function is only re-run when the listed dependency values change.

💡Referential Equality

Referential equality in JavaScript means that two references point to the exact same object in memory. The video discusses how `useMemo` can be used to ensure that objects or arrays are only considered changed when their actual content changes, not just when a new reference is created.

💡Theme Styles

Theme styles refer to the visual design aspects of a user interface, such as colors and typography, that can be toggled between light and dark modes. In the video, theme styles are used as an example to illustrate how `useMemo` can prevent unnecessary re-renders when the style object's reference changes without actual content alteration.

💡Free Web Hosting

The term 'free web hosting' is mentioned in the context of a sponsorship offer. It is not directly related to the main technical content of the video but serves as an example of how the presenter might integrate promotional content into the video.

Highlights

Introduction to React's use memo hook and its purpose.

Explanation of when to use use memo to avoid unnecessary re-renders.

Demonstration of a slow function within a React component causing performance issues.

The concept of memoization in React to cache values and avoid re-computation.

How use memo can optimize performance by caching the result of a slow function.

Live coding example showing the impact of use memo on the app's performance.

Instantaneous theme toggle after implementing use memo, showcasing its effectiveness.

Discussion on the potential overheads of using use memo in terms of performance and memory.

Guidelines on when to use use memo based on the necessity of performance benefits.

Introduction to referential equality and its significance in JavaScript.

Example of how use memo can be used to ensure referential equality for objects or arrays.

Use case of use memo to prevent unnecessary re-renders due to object reference changes.

Explanation of the two primary use cases for use memo: optimizing slow functions and ensuring referential equality.

Recommendation to use use memo judiciously to avoid unnecessary memory and performance overhead.

Link to a full React course for deeper understanding provided in the video description.

Summary of the key points about use memo for optimizing React components.

Closing remarks and thanks for watching the React hooks series video.

Transcripts

play00:00

hello everyone welcome back to my react

play00:02

hooks series or in this video we're

play00:04

gonna take a look at use memo how it

play00:06

works and when you should actually use

play00:08

it and if you're interested in diving

play00:10

into react even deeper make sure to

play00:12

check out my full react course which I'm

play00:14

gonna link down in the description below

play00:18

have you wanted free web hosting that

play00:21

doesn't suck well you're in luck because

play00:23

today's video sponsor atlanticnet is

play00:26

giving you an entire year long free

play00:28

trial of their hosting and if you use

play00:31

the code Kyle when you check out you're

play00:33

gonna get an additional $50 of credit

play00:35

that you can use towards whatever you

play00:36

want on the hosting platform on top of

play00:39

that this hosting platform has powerful

play00:41

servers with great data reliability and

play00:43

redundancy so you know that your site is

play00:45

going to be there and running with the

play00:47

data you want it to so make sure you use

play00:49

the code Kyle in the link down in the

play00:51

description below to get your free

play00:52

hosting welcome back to web data

play00:55

simplified my name is Kyle and my job is

play00:57

to simplify the web for you so you can

play01:00

start building your dream project sooner

play01:01

so if that sounds interesting make sure

play01:03

you subscribe to the channel for more

play01:05

videos just like this now to get started

play01:07

I just have some really basic

play01:09

boilerplate code set up for us to test

play01:11

our application I'm gonna walk through

play01:13

it real quick so you know exactly what

play01:14

we're doing I just have a simple single

play01:17

component called app which has two

play01:19

pieces of state one is a number which we

play01:21

can control by this input over here on

play01:23

the right and the second one is a

play01:25

boolean for dark or light which is

play01:27

toggled by this change theme button on

play01:29

the right side of our screen then what

play01:32

we do is we have a function which

play01:34

doubles our number so just multiplies by

play01:36

two but this function is very slow if I

play01:38

scroll down here you can see I just have

play01:40

a really long for loop that just loops

play01:43

doing nothing for a really long time to

play01:44

emulate what would happen in a really

play01:47

slow long-running complex function

play01:49

obviously since this function just

play01:51

multiplies by two all this code is doing

play01:53

is making the function really slow and

play01:55

if I change this number for example by

play01:57

clicking this up arrow you're gonna see

play01:59

it takes about a second half a second

play02:01

for it to actually double the number so

play02:03

you can see this function is quite slow

play02:04

to execute now continuing onward we just

play02:08

have a variable here which is taking

play02:09

this dark boolean and changing if we

play02:11

have a darker

play02:12

theme down here and then lastly over

play02:14

here we just have the output code which

play02:16

changes our number when we update here

play02:18

and also toggles our theme when we click

play02:20

this button so that's just the basics of

play02:23

our code and you may think okay this is

play02:26

fine code it's working great and the

play02:28

slowness is you know not that bad but it

play02:30

only is gonna be slow going we update

play02:31

our number but actually that's incorrect

play02:33

thinking if we click our change theme

play02:36

button you're gonna notice we have the

play02:37

same delay I'm going to click it now you

play02:39

can see it takes about half a second to

play02:41

a second for it to actually change the

play02:43

actual theme and the reason for that is

play02:45

because one you update state and react

play02:47

it's going to re-render your entire

play02:49

component so it's going to run this

play02:50

entire function from top to bottom which

play02:53

means that this slow function gets

play02:55

called every single time that we render

play02:57

our app component so whether we're

play03:00

changing the theme whether we're

play03:01

actually updating the number here or

play03:03

whether some other component is causing

play03:06

this component to re-render you're going

play03:08

to be forcing it to go through that slow

play03:10

function over and over and over again

play03:11

and this is a really big performance

play03:14

problem when you have these slow

play03:15

functions that don't really change that

play03:17

often so react has a built in way to

play03:21

solve this with a hook which is called

play03:23

use memo so we can import this views

play03:26

memo hook just like this and memo here

play03:28

stands for memoization which essentially

play03:31

is the idea of caching a value so you

play03:33

don't have to recompute it every single

play03:35

time so in our example this slowed

play03:38

function here takes an input of a number

play03:40

and it's always going to give us the

play03:42

same output every time we give it the

play03:44

same input so we can cache that input

play03:46

value number and the output it gives us

play03:49

that way if the number doesn't change we

play03:51

don't have to recalculate our SLO

play03:53

function over and over and over again

play03:55

and the easy way to use this is we just

play03:58

call use memo and we're going to pass it

play04:01

in a function and this function is going

play04:03

to be the thing that we actually

play04:04

memorize so this is the thing that we're

play04:06

caching which in our case is going to be

play04:08

this slow function we just want to make

play04:10

sure we return this slow function here

play04:12

get the result from it and then just

play04:15

like all of the other hooks that we

play04:16

talked about like use effect for example

play04:18

we're going to have a list of

play04:19

dependencies here and in our case the

play04:22

the dependency of this is going to be

play04:24

our number here our number is the only

play04:26

thing that changes and when our number

play04:28

changes we need to rerun the code inside

play04:31

this use memo hook but if our number

play04:33

doesn't change we don't need to rerun

play04:35

this slow function code so with that one

play04:38

simple change let's save and see what

play04:40

happened to our app it's loading over

play04:42

here we can change this to for example 1

play04:44

and you can see it has a kind of delay

play04:46

change it up again it's going to have a

play04:47

delay when we click Change theme you're

play04:50

going to notice this is instantaneous I

play04:52

can click it as much as I want to and

play04:53

that's because when we go through our

play04:55

code we click Change theme it causes our

play04:58

component to re-render so it calls this

play05:00

function does all this stuff and it gets

play05:02

down to use memo and it says well our

play05:04

number is exactly the same as what it

play05:06

was last time so we're not gonna recall

play05:08

this slow function here because we

play05:11

already know what the result is it's the

play05:12

exact same thing as it was last time so

play05:15

we're saving ourselves from having to

play05:16

recalculate this number with the slow

play05:19

function and we only are forcing

play05:21

ourselves to do this when we actually

play05:22

update this number instead of our input

play05:24

here so we're essentially only running

play05:26

this slow code when we have to and not

play05:29

running it when we don't actually need

play05:30

to now this seems really nice and you

play05:33

may think let me just use memo

play05:34

everywhere why not just memorize

play05:36

everything like this theme style is here

play05:38

why don't I memorize that based on this

play05:40

dark boolean variable and the reason you

play05:42

don't want to memorize everything is

play05:44

because it does give you some

play05:45

performance overheads and some memory

play05:48

overhead for example this used memo

play05:50

function must be called every single

play05:51

render of your component so you're

play05:53

calling an additional function and also

play05:56

it's saving the value this previous

play05:58

value in some memory variable so you're

play06:01

forcing your memory to get larger every

play06:03

time you use memo because you have to

play06:05

store an additional variable in memory

play06:07

to store that previous value now this

play06:09

isn't a huge deal but if you start to do

play06:11

this everywhere in your application

play06:13

especially where you don't need it it's

play06:15

going to cause additional memory usage

play06:17

and additional performance problems when

play06:19

just not using it would have been better

play06:21

so I highly recommend you only use memo

play06:23

in this case when you actually need the

play06:26

performance benefits when the function

play06:28

you're calling is incredibly slow then

play06:30

use memo is great but there's also a

play06:33

second use case for used memo

play06:36

and that is something called the

play06:37

referential equality and if you aren't

play06:39

really familiar with value versus

play06:41

reference in JavaScript I have a video

play06:43

on that topic I'll link in the cards in

play06:44

description but essentially what that is

play06:46

saying is when you try to compare two

play06:48

different variables in JavaScript it's

play06:50

going to compare the reference in the

play06:52

case of objects and arrays so for

play06:55

example this theme Styles here is a

play06:57

specific object and if I were to

play06:59

duplicate this theme styles for example

play07:01

theme Styles to right here you would

play07:04

think that theme styles and theme style

play07:06

2 are equal to each other but in

play07:08

JavaScript they reference two different

play07:10

objects they have the same values in the

play07:12

object but the actual reference to the

play07:14

object itself is different these two

play07:16

values are actually not equal to each

play07:19

other

play07:19

which is something really important and

play07:21

as you know instead of hooks and react

play07:24

we have this array here all of our

play07:26

dependencies and when our dependencies

play07:28

change it's going to rerun our hook so

play07:31

let's click a quick example where we

play07:33

have a use effect and we want to run

play07:35

this use effect every single time that

play07:38

our theme styles here changes so we're

play07:41

just gonna have a really simple

play07:43

console.log theme that changed and down

play07:47

here inside of our dependencies I'm

play07:49

going to have our theme styles let's

play07:51

just get rid of this console down here

play07:52

and of course we need to make sure we

play07:55

import use effect just like that and now

play08:00

if I just really quickly inspect this

play08:01

page here pull this over go to the

play08:04

console oops console you can see we get

play08:07

our theme changed being printed out and

play08:08

when we change our theme you can see

play08:10

it's continually printing out theme

play08:11

changed but a problem you'll notice if I

play08:13

clear this out is when we change our

play08:15

number it's also causing this theme

play08:17

change to be run and the reason for that

play08:20

is that referential equality what's

play08:22

happening is every time we run our

play08:24

function we get a new theme styles

play08:26

object being created and this new theme

play08:29

style object is not the same as the old

play08:31

theme styles even though they have the

play08:33

exact same values in the object the

play08:36

reference different places in memory and

play08:38

that's really important to know so in

play08:41

order to make sure that we only ever run

play08:43

use effect when our theme style object

play08:46

actually gets real we can use memo

play08:49

so what we can do is wrap this in a used

play08:52

memo make sure you pass it a function

play08:54

and in here we're just going to return

play08:57

to that object you just indent all this

play08:59

properly and in here for our

play09:01

dependencies we're just gonna put that

play09:03

dark variable because that's the only

play09:04

thing that this object depends on now if

play09:07

we were to rerun this you can see a

play09:09

change in our theme causes this to

play09:11

update our theme logs it out but when we

play09:13

change our number you're gonna notice we

play09:16

don't actually get anything printed in

play09:17

our console and only when we click

play09:19

change theme and the reason for this is

play09:21

that now we are wrapping this object

play09:24

inside of memorisation essentially if

play09:26

our dark variable doesn't change

play09:28

we don't read 8 our theme styles so we

play09:31

get the exact same reference as we had

play09:34

the previous time we rendered our app so

play09:36

now our use effect is comparing our old

play09:39

theme styles with our new theme styles

play09:41

but they both reference the exact same

play09:43

object so these are the two big use

play09:46

cases for a use memo the first and most

play09:49

obvious is when you want to make a slow

play09:51

function we wrap it in this use memo so

play09:53

that doesn't recompute every single time

play09:55

you render your component and it only

play09:57

computes when you actually need the

play09:59

value from that function since the

play10:01

inputs actually changed the second use

play10:03

case which is a little bit trickier is

play10:05

this idea of a referential equality

play10:07

whenever you want to make sure the

play10:09

reference of an object or an array is

play10:12

exactly the same as it was the last time

play10:14

you rendered if none of the internal

play10:16

workings changed you're gonna want to

play10:18

use memo here to make sure that you only

play10:20

update the reference of that object

play10:22

whenever the actual contents of the

play10:24

object change instead of updating every

play10:26

single time you render and that's all

play10:29

there is to the used memo hook if you

play10:31

enjoyed this video make sure to check

play10:32

out my full react course linked in the

play10:34

description to get a full overview of

play10:36

everything you need to know about react

play10:38

thank you very much for watching and

play10:40

have a good day

Rate This

5.0 / 5 (0 votes)

Related Tags
ReactHooksuseMemoPerformanceOptimizationJavaScriptCodingWeb DevelopmentMemoizationReferential Equality