What is React.memo and how does it work?
React.memo
is a higher-order component (HOC) that helps you optimize functional components by memoizing them.
When you wrap a component with React.memo
, React will remember the last rendered output and skip rendering the component again if its props have not changed.
How it works:
- Without
React.memo
, a parent component re-rendering will cause all its children to re-render, even if their props are the same. - With
React.memo
, React compares the previous props with the new ones using a shallow comparison. - If the props are the same, the component’s render is skipped, saving CPU cycles.
Example:
const MyComponent = React.memo(function MyComponent(props) { return <div>{props.title}</div>; });
Key points:
React.memo
only works for functional components.- It uses a shallow comparison for props by default.
- You can provide a custom comparison function if needed.
function areEqual(prevProps, nextProps) { return prevProps.title === nextProps.title; } export default React.memo(MyComponent, areEqual);
When to use:
- For "pure" functional components (components that render the same output given the same props).
- When child components are receiving complex props that don't often change.