How to decrease unnecessary re-renders

circle-exclamation

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.

circle-info

Wrapping everything in React.memo can actually slow down your app in some cases and in all cases it makes your code more complex. So it's much better to use it more intentionally.

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