How to use R...
How to use R...
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.
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.
const MyComponent = React.memo(function MyComponent(props) {
// Component implementation
return <div>{props.children}</div>;
});
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).
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);
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
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào