When to Use the React memo() Higher-Order Component?

The React memo() higher-order component is useful for optimizing performance in situations where:

  • A component frequently re-renders with the exact same props, and;
  • The cost of re-rendering it is noticeable to the user.

Please note that the props must be shallowly equal for memoization to be effective.

That being said, you should keep the following in mind:

  • Memoization may not be necessary if the cost of re-rendering the component is negligible, and the performance impact is not noticeable to the user;
  • Memoization won't provide any benefits if the props passed down to the component are always different, such as when passing an object, array, or a function defined during rendering, unless they're themselves memoized using useMemo() and/or useCallback();
  • Memoized components will still re-render if their own state changes, or if a value passed by context changes that the component uses.

Please note that there is no real benefit of wrapping a component with memo() in other cases than those mentioned above. However, you may still do so without causing any major issues.

For example, consider the following component that has a reactive value used for storing the selected state of "Dark mode":

// App.jsx
import React, { useState } from 'react';
import Child from './Child';

const App = () => {
  const [isDark, setIsDark] = useState(false);

  return (
    <>
      <label>
        <input
          type="checkbox"
          checked={isDark}
          onChange={(e) => setIsDark(e.target.checked)}
        />
        Dark mode
      </label>
      <Child />
    </>
  );
};

export default App;

This component also renders the following "Child" component (along with the "Dark mode" checkbox):

// Child.jsx
import React from 'react';

const Child = () => {
  console.log('rendered');

  return <div>Child</div>;
};

export default Child;

In this example, the Child component unnecessarily re-renders everytime you toggle the "Dark mode" checkbox in the parent component.

To prevent this from happening, you can wrap the Child component with memo(), for example, like so:

import React, { memo } from 'react';

// ...

export default memo(Child);

Now, everytime you toggle "Dark mode", the Child component will not be re-render each time.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.