Prevent Unnecessary Component Rerenders with React memo

InstructorKent C. Dodds

Share this video with your friends

Send Tweet

You only want to re-render components when the data for that component has changed. Often times you'll find that multiple instances of a component will re-render when the props change for one of them.

With React.memo, you can now pass a stateless functional component to it and it will ensure that it does not rerender unless the props given to the component changes. In this lesson, you'll learn how to implement this with your stateless functional components.

NOTE: This does not work for Class based React Components, use PureComponent or shouldComponentUpdate.

Craig
~ 6 years ago

What course is this from?

Kent C. Doddsinstructor
~ 6 years ago

It's part of a playlist: http://kcd.im/hooks-and-suspense

Craig
~ 6 years ago

Thanks Kent, learning a lot from your work. Appreciate ya!

Babak Badaei
~ 6 years ago

@Kent, couldn't this work as a cache? Is the advantage of react-cache that it works with Suspense?

Kent C. Doddsinstructor
~ 6 years ago

They're different use cases entirely. You could use them together if you want though.

Babak Badaei
~ 6 years ago

@Kent Right, I looked into it further and see that React.memo isn't memoizing per function call, it is memoizing per re-render

https://codesandbox.io/s/8nr4xqrwj8

Here you will see the Hello component rendered twice. Each time the function is actually called, the output is not cached; however, the function isn't called each time the App is re-rendered.

Jwan Khalaf
~ 5 years ago

@Kent I am building a simple lyrics app. A user gets a list of artists, once you click on an artist, you get a list of lyrics for that artist, and a further click on the lyric, shows the actual lyric to read.

I have a question about performance. Say I have a massive list of 6000 artists, performance wise, it isn't wise to load a list of 6000 artists on that first page render, what is the best way of achieving a list where more artists are loaded as the user scrolls down?

So initially load like 15 artists, and then as the user scrolls down the page, more artists are loaded.

Ajay Kumar
~ 5 years ago

@Jwan Windowing might be the answer.

Eric Laursen
~ 5 years ago

What happened to the codesandbox ?! :( I got "Not Found We could not find the sandbox you're looking for."

Kent C. Doddsinstructor
~ 5 years ago

Try again Eric, it's showing up for me.

Jwan, for displaying those artists, I recommend using react-window.