Current section: Element Optimization 33 exercises
solution

Memoize Elements

Loading solution

Transcript

00:00 There's really not a lot that we have to change here. We just want to say, hey, I want this React element to be the same as long as the name is unchanged. That's what we're saying. So useMemo from React, and this is what we're going to get. We depend on the name, boom, we are done.

00:17 So now, useMemo will make sure that we always receive the same thing that we gave it the previous time, so long as the name remains unchanged, which is exactly our desired results here. So if I record, and I'm going to change the name, Cody exclamation point, and then we're going to change the color.

00:35 So both of those trigger to re-render, we'll see that in the profile, but then incrementing the app count and the main count, that should not trigger any re-renders. Let's take a look. So footer re-rendered because the props changed, the name changed, that makes total sense. If we look at this one, the context changed,

00:53 total sense, and then here, oh my goodness, there is a missing component in here because we didn't need to re-render, and we got the same React element that time as we did the previous time because the name was unchanged. Sweet, and then of course, the main is the only one that's re-rendering for that.

01:12 So there you go. Another approach to preventing a re-render of a React component is by memoizing the React element that you get from it, and then just listing the props in useMemo.