React: memo, useMemo, useCallback and how to use it to boost your app performance

React.memo

In this article, this is the only function (HOC) that can work with both: class components and functional components. It was introduced in 2019 as a replacement forReact.PureComponent that has only one job: compare props and avoid rendering when they don’t change. Additionally, you can provide a custom comparator as a second argument.

  1. No props. If your component is completely isolated and does not have any props at all — this is your obvious candidate. You can wrap its export with React.memo and it will be an efficient and fast rendering fence (an isolation layer that prevents underlying code/components from execution) and your component will re-render only when its internal state has changed.
  2. The amount of properties is relatively small. Sometimes it could be faster to render a component than to compare a long list of props. There is no golden rule, you will need performance testing to identify what option works faster.
  3. Rarely changing props of primitive types. When you pass string, number, or boolean props it’s easy to compare and hard to get into the situation when you accidentally provide a new variable (like object, array or a function) every time.

useCallback and useMemo

First, I’d like to note that they use the same implementation, the only difference is that useMemo returns a result of a function you pass into it, and useCallback returns a function itself. And since they are essentially the same, I will be referring to useMemo.

  • Wrap it with React.memo
  • Ensure all props are either primitive or wrapped with useCallback/useMemo

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Yury Kozyrev

Yury Kozyrev

Former Yandex Software Engineer, passionate Engineering Manager in Berlin