Middle
In which cases should React.memo be used?
sobes.tech AI
Answer from AI
React.memo is used to optimize functional components by preventing unnecessary re-renders when props haven't changed.
Use React.memo when:
- The component renders frequently with the same props.
- The rendering of the component is costly in terms of performance.
- The parent component updates often, but the child component should not re-render unnecessarily.
Example:
const MyComponent = React.memo(function MyComponent(props) {
// component will only re-render if props change
return <div>{props.value}</div>;
});
It's important to remember that React.memo performs a shallow comparison of props, so for complex objects, a custom comparison function might be needed.