How to decrease unnecessary re-renders
Fix your slow renders first. Then deal with the "unnecessary re-renders"
A React Component can re-render for any of the following reasons:
Its props change
Its internal state changes
It is consuming context values that have changed
Its parent re-renders
When our components are re-rendered even though no DOM updates were needed, we can optimize that component to be memoized via React.memo
.
function Menu({
items,
getMenuProps,
getItemProps,
highlightedIndex,
selectedItem,
}) {
return (
<ul {...getMenuProps()}>
{items.map((item, index) => (
<ListItem
key={item.id}
getItemProps={getItemProps}
item={item}
index={index}
isSelected={selectedItem?.id === item.id}
isHighlighted={highlightedIndex === index}
>
{item.name}
</ListItem>
))}
</ul>
)
}
Menu = React.memo(Menu)
Last updated
Was this helpful?