How to use React.memo for performance optimization



Image not found!!

React.memo is a higher-order component (HOC) in React that memoizes a functional component to prevent unnecessary re-renders. This can be particularly useful for optimizing performance in your React applications. By default, React components will re-render whenever their parent component re-renders, even if the props passed to them remain unchanged. React.memo helps in avoiding these unnecessary re-renders.

Here's how you can use React.memo:

jsx
import React from 'react'; const MyComponent = ({ prop1, prop2 }) => { // render logic here return ( <div> <p>{prop1}</p> <p>{prop2}</p> </div> ); }; // Memoize the component const MemoizedComponent = React.memo(MyComponent); // Now use MemoizedComponent instead of MyComponent in your application

In the example above, MyComponent is a functional component that takes two props (prop1 and prop2). By wrapping it with React.memo, a memoized version of the component is created and returned by React.memo. This memoized component will only re-render if its props have changed.

Keep in mind the following points:

  1. Props Equality Check:

    • React.memo performs a shallow comparison of the props to determine whether the component should re-render.
    • If the props are objects or arrays, make sure that their references are different if their contents are the same. Otherwise, React.memo might not detect changes.
  2. Custom Comparison Function:

    • If you need more control over the comparison of props, you can provide a custom comparison function as the second argument to React.memo. This function receives the previous and current props and should return true if the props are equal and false otherwise.
    jsx
    const arePropsEqual = (prevProps, nextProps) => { // Custom logic to determine equality return prevProps.prop1 === nextProps.prop1 && prevProps.prop2 === nextProps.prop2; }; const MemoizedComponent = React.memo(MyComponent, arePropsEqual);
  3. Functional Components Only:

    • React.memo only works with functional components. Class components can use the shouldComponentUpdate lifecycle method for similar optimizations.

By using React.memo strategically, you can improve the performance of your React application by avoiding unnecessary renders of components when their props haven't changed.