React.memo
`React.memo` is a higher-order component (HOC) that prevents unnecessary re-renders of a component if its props haven't changed. It is used for performance optimization by memoizing entire components.
Key concepts
React.memo
A higher-order component (HOC) that prevents unnecessary re-renders of a component if its props haven't changed. Used for performance optimization by memoizing entire components.
Step by step
How It Works:
- The `ChildComponent` only re-renders when the `value` prop changes, thanks to `React.memo`.
When to Use React.memo:
- For functional components that rely heavily on props and do not depend on parent re-renders.
- In conjunction with `useCallback` and `useMemo` to optimize performance.
Examples
React.memo Example:
import React, { useState } from 'react';
const ChildComponent = React.memo(({ value }) => {
console.log('Child Rendered');
return <p>Child Value: {value}</p>;
});
function ParentComponent() {
const [parentValue, setParentValue] = useState(0);
const [childValue, setChildValue] = useState(0);
return (
<div>
<button onClick={() => setParentValue(parentValue + 1)}>Increment Parent</button>
<button onClick={() => setChildValue(childValue + 1)}>Increment Child</button>
<ChildComponent value={childValue} />
</div>
);
}Stuck on this one? Talk to Sumit.
Keys: F focus mode · ← → previous / next topic · Esc leave focus