#Day85 of #100daysofcode
Today I learned about the React.memo higher order component.
In React, a component can re-render for any of the following reasons:
- Its props change
- Its internal state changes
- It is consuming context values which have changed
- Its parent re-renders
But what if we don’t want a particular component to re-render unless and until there’s a good reason to re-render it(like the update needs to reflect on the DOM)?
For the above-mentioned reason, we can simply use React.memo to ensure that the component only gets re-rendered until and unless its own props get changed.
Here’s an example implementation on how we can do the same on a ListItem which is a child component of a really long List Component:
function ListItem({
getItemProps,
item,
index,
selectedItem,
highlightedIndex,
...props
}) {
const isSelected = selectedItem?.id === item.id
const isHighlighted = highlightedIndex === index
return (
<li
{...getItemProps({
index,
item,
style: {
fontWeight: isSelected ? 'bold' : 'normal',
backgroundColor: isHighlighted ? 'lightgray' : 'inherit',
},
...props,
})}
/>
)
}
The above component will re-render whenever its parent gets re-rendered, and that can cause serious performance issues when the list is significantly long.
Now, we can simply wrap this ListItem component using the following syntax:
ListItem = React.memo(ListItem)
And this will avoid all the unnecessary re-render we just discussed.