Câu hỏi phỏng vấn Reactjs
Câu hỏi

How to use R...

Câu trả lời

React.memo() is a higher-order component (HOC) provided by React for optimizing performance in functional components. It is particularly useful when you want to control the re-rendering behavior of components to avoid unnecessary updates, which can lead to improved performance, especially in larger or complex applications.

How to Use React.memo()

  1. Basic Usage:
    React.memo() is used to wrap a functional component. The component will only re-render if its props change. This is done by performing a shallow comparison of the previous and new props.

    javascript Copy
    const MyComponent = React.memo(function MyComponent(props) {
      // Component implementation
      return <div>{props.children}</div>;
    });
  2. Custom Comparison Function:
    Optionally, you can provide a second argument to React.memo() — a custom comparison function that tells React how to compare the old props with the new ones. This function should return true if the props are equal (i.e., the component should not re-render), and false if they are not equal (i.e., the component should re-render).

    javascript Copy
    const arePropsEqual = (prevProps, nextProps) => {
      // Return true if passing nextProps to render would return
      // the same result as passing prevProps to render,
      // otherwise return false
      return prevProps.someValue === nextProps.someValue;
    };
    
    const MyComponent = React.memo(function MyComponent(props) {
      // Component implementation
      return <div>{props.someValue}</div>;
    }, arePropsEqual);

When to Use React.memo()

  • Frequent Re-renders with Same Props: Use React.memo() when the component has the potential to re-render often with the same props. This is common in components deep in the component tree of large applications, where upper-level components might update state or props frequently[1][2][3][4].

  • Performance Optimization: If profiling indicates that a component is a bottleneck due to frequent unnecessary re-renders, wrapping it in React.memo() can boost performance by memoizing the last rendered ou...

expert

expert

Gợi ý câu hỏi phỏng vấn

middle

What's the typical flow of data like in a React + Redux app?

junior

What is state in React?

junior

What does it mean for a component to be mounted in React

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào