Current section: Optimize Rendering 33 exercises
Problem

Custom Comparator

Loading exercise

Transcript

00:00 We've got another situation we want to optimize here. When we highlight items and unhighlight them, or just change them in any way using the keyboard, this is a performance problem. So let's click on the profiler, record this profile, highlight, unhighlight, and stop. And you'll see we got that red going on again.

00:17 Good grief, 60 milliseconds to re-render. Now we're in a 6x slowdown on throttling our CPU and all that, but still, that is not great. And if you dive down in here, you'll see our components are in there getting re-rendered. Unnecessarily, we don't want that. So what we need to do,

00:37 and actually you can also go to your profile here, record, and then highlight and unhighlight, and you'll see, yep, all of our list items are getting re-rendered again, even though we're memoizing. And so the problem is that one of the things that our components depend on is the highlighted index. So if that ever changes,

00:56 then all of them need to re-render because of the highlighted index. But we can kind of tweak this, we can optimize it even further by saying what change in the highlighted index necessitates a re-render for our component. So here's an example of what we call the comparator function. You pass that to the second argument of memo,

01:15 and you're gonna get the previous props and the next props, and then you determine what are the changes that are going to impact me. So in our case, it's just the avatar URL and the name. If there's other things about the user that changed, we don't need to re-render. So here we check, did the avatar change or the name change?

01:32 And we return true if we don't want to re-render. So if they're both unchanged, this should be and the name is unchanged. So if both of these things are unchanged, then we don't need to re-render. If either one of them changed though, we want to re-render. So that is your objective in this exercise

01:50 is to go to our memoization for the list item and perform a calculation to determine whether or not this thing should re-render. Have a good time.