React.memo is a higher-order component that helps to prevent unnecessary re-renders of functional components by memoizing the result. Itβs a powerful optimization tool that improves performance, especially in large-scale React apps.
When a component receives the same props again, React.memo prevents it from re-rendering. This is useful in components that render frequently or have expensive rendering logic.
const MyComponent = React.memo(function MyComponent(props) {
return <div>{props.name}</div>;
});
React.memo?Without memoization, even unchanged props will re-trigger rendering:
function User({ name }) {
console.log("Rendering User");
return <p>Hello, {name}</p>;
}
function App() {
const [count, setCount] = useState(0);
return (
<div>
<User name="Rahul" />
<button onClick={() => setCount(count + 1)}>Click</button>
</div>
);
}
Using React.memo, User component won't re-render unless its props change:
const User = React.memo(function User({ name }) {
console.log("Rendering User");
return <p>Hello, {name}</p>;
});
React.memo only works for functional components.Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!