ReasonJun

React : React.memo (comparison method) 본문

Frontend/React

React : React.memo (comparison method)

ReasonJun 2023. 6. 13. 13:22
728x90

React.memo is a higher-order component (HOC) provided by React that aims to optimize functional components by preventing unnecessary re-renders. It is similar to the PureComponent class component optimization but designed for functional components.

 

By wrapping a functional component with React.memo, React will automatically memoize the component and only re-render it if its props have changed. If the component is re-rendered with the same props, React will return the previously rendered result, avoiding the need to recompute the component's output.

 

Here's an example of how to use React.memo:

import React from 'react';

const MyComponent = React.memo(({ prop1, prop2 }) => {
  // Component logic and rendering
});

export default MyComponent;

In this example, the MyComponent functional component is wrapped with React.memo. React will compare the props passed to MyComponent between renders. If the props remain the same, React will reuse the previous rendered output. If the props change, React will re-render the component.

 

It's important to note that React.memo performs a shallow comparison of the props, meaning that it compares the prop values by reference. If the prop values are objects or arrays, changes within those objects or arrays might not be detected, and the component might not re-render as expected. In such cases, you might need to consider additional techniques like immutability or using a state management library to ensure proper updates.

 

The usage of React.memo can be beneficial in scenarios where functional components have expensive computations or where re-rendering can be avoided to optimize performance. However, it's essential to use it judiciously and consider the specific needs of your components, as memoization may not always be necessary or appropriate for every situation.

 

Caution

When you think of components that most often have different props when rendered, it is difficult to benefit from memoization techniques. Even if you wrap a component whose props change frequently with React.memo() , React will do two things every time you re-render.

  1. Perform comparison function for equality comparison of previous props and next props.
  2. Since the comparison function will almost always return false, React compares the previous render with the next render.

Most of the comparison function returns false, so comparing props becomes unnecessary.

 

conclusion

To optimize rendering performance in React, separate React components and use React.memo. Also, using React.memo is not always good, so it is good to use it after checking if there is a performance benefit using a profiler.

728x90
Comments