|
1 | 1 | # Custom Comparator
|
2 | 2 |
|
3 |
| -Hover over one of the list items and notice they all re-render |
| 3 | +👨💼 We've improved things so the `ListItem` components don't rerender when there |
| 4 | +are unrelated changes, but what if there are changes to the list item state? |
| 5 | + |
| 6 | +Hover over one of the list items and notice they all rerender. But we really |
| 7 | +only need the hovered item to rerender (as well as the one that's no longer |
| 8 | +highlighted). |
| 9 | + |
| 10 | +So let's add a custom comparator to the `memo` call in `ListItem` to only |
| 11 | +rerender when the changed props will affect the output. |
| 12 | + |
| 13 | +Here's an example of the comparator: |
| 14 | + |
| 15 | +```tsx |
| 16 | +const Avatar = memo( |
| 17 | + function Avatar({ user }: { user: User }) { |
| 18 | + return <img src={user.avatarUrl} alt={user.name} /> |
| 19 | + }, |
| 20 | + (prevProps, nextProps) => { |
| 21 | + const avatarChanged = prevProps.user.avatarUrl !== nextProps.user.avatarUrl |
| 22 | + const nameChanged = prevProps.user.name !== nextProps.user.name |
| 23 | + return avatarChanged || nameChanged |
| 24 | + }, |
| 25 | +) |
| 26 | +``` |
| 27 | + |
| 28 | +So even if the user object changes, the `Avatar` component will only rerender if |
| 29 | +the `avatarUrl` or `name` properties change. |
| 30 | + |
| 31 | +By default, React just checks the reference of the props, so by providing a |
| 32 | +custom comparator, we override that default behavior to have a more fine-grained |
| 33 | +control over when the component should rerender. |
| 34 | + |
| 35 | +So let's add a custom comparator to the `ListItem` component so it only rerenders |
| 36 | +when absolutely necessary. |
| 37 | + |
| 38 | +Pull up the React Profiler and the DevTools Performance tab to see the impact |
| 39 | +of this optimization as you hover over different list items. |
0 commit comments