Current section: Element Optimization 33 exercises
Problem

Memoize Elements

Loading exercise

Transcript

00:00 The world is messy yet again, and it's not always so simple as just consuming one context value. So we have this new feature where the footer accepts a name prop, and that name can be changed through this input. And so changing the name and changing the color should re-render the footer,

00:17 but anything else, changing the app count or, yeah, really just changing the app count or changing the count that's inside of main should not re-render the footer. So we've just undone all the cool work that we've done so far because the footer now accepts a prop with the name. Now, you might be thinking, oh, okay, so we just make another context for the name.

00:37 No, please don't just make context for every single thing that your component can have, unless you've tried everything else and it doesn't work. But yeah, there's another way to do this, and we're going to explore all the different approaches that we can take. So in this one, we're going to be using useMemo. What? Yeah, this is going to be interesting.

00:58 So we're going to memoize the component so that we get the same React element every time so long as the name is unchanged. So by the time you're finished, you should be able to have it change when you change the name. You should have it re-render when you change the color,

01:16 but it should not re-render when you increment the app count or the main count. And right now, you'll notice that it is properly re-rendering when we change the name and the color, but it's improperly re-rendering when we change the app count because the app count triggers a re-render of this UI. But there is a way with useMemo around this guy

01:37 that will allow us to avoid that re-render when we change the app count. And that, again, is taking advantage of the element reuse feature that is built into React. And then, of course, when we are incrementing the count, that is all contained inside of the main component.

01:56 So that's not going to bother us at all because we're composing properly and we don't have any problems there. Okay, great. So let's useMemo.