React.memo is a higher-order component used in React to optimize performance by preventing unnecessary re-renders of functional components. It works by memoizing the result of a component and only re-rendering it if its props change. This is useful for performance optimization in functional components that render the same output given the same props.
import React from 'react'; const MyComponent = ({ count }) => { console.log('Component re-rendered'); returnCount: {count}; }; export default React.memo(MyComponent);
In this example, MyComponent will only re-render if the count prop changes. If the parent component re-renders but the count prop remains the same, MyComponent won't re-render, reducing unnecessary computations.
By default, React.memo performs a shallow comparison of props, but you can also provide a custom comparison function for deeper checks if needed:
const MyComponent = React.memo((props) => { /* component code */ }, (prevProps, nextProps) => { // return true if props are equal, false otherwise return prevProps.someValue === nextProps.someValue; });
This can further optimize performance when you have more complex prop structures.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3