CodePark/ questions / Performance: re-renders & memo
START PRACTICINGPRACTICE
Frontend question · React › Performance: re-renders & memo

What does React.memo do, and why does it sometimes fail to prevent re-renders?

memo(Component) returns a memoized component that skips rendering when its props have not changed. When the parent re-renders, React compares each new prop with the previous one using Object.is. This is a shallow comparison. If all props are equal, React skips the render. You can pass your own comparison function as the second argument.

It fails when a prop gets a new reference every render. Common causes:

  • an inline object, like style={{ color: 'red' }}
  • an inline arrow function
  • an array created during render
  • JSX passed as children, which is a new element each time

Fix these with useMemo or useCallback, or move constants outside the component.

memo also does not stop re-renders caused by the component's own state or by a context it reads. It is a performance optimisation, not a guarantee. The component must still work correctly without it.

  • memo skips a re-render when the props are shallowly equal.
  • You can pass an optional custom comparison function.
  • New object, array, function or children props defeat it.
  • It does not block updates from the component's own state or context.
  • It is an optimisation, not a guarantee of fewer renders.