React.memo
is a higher-order component in React that's used for optimizing functional components by preventing unnecessary re-renders. It's similar in purpose to the shouldComponentUpdate
lifecycle method in class components. When you wrap a functional component with React.memo
, it will only re-render if its props have changed.
Here's a simple example to illustrate the use of React.memo
:
import React, { useState } from 'react';
// Regular functional component
const ChildComponent = ({ name }) => {
console.log('ChildComponent rendered');
return <p>{name}</p>;
};
// Wrap the functional component with React.memo
const MemoizedChildComponent = React.memo(ChildComponent);
const ParentComponent = () => {
const [count, setCount] = useState(0);
const incrementCount = () => {
setCount(prevCount => prevCount + 1);
};
return (
<div>
<button onClick={incrementCount}>Increment Count</button>
{/* Only MemoizedChildComponent will re-render when its props change */}
<MemoizedChildComponent name={`Count: ${count}`} />
</div>
);
};
const App = () => {
return <ParentComponent />;
};
export default App;
In this example:
-
ChildComponent
is a simple functional component that takes aname
prop and renders a paragraph element with the given name. It logs a message to the console when it renders. -
MemoizedChildComponent
is created by wrappingChildComponent
withReact.memo
. This means thatMemoizedChildComponent
will only re-render if its props change. -
In the
ParentComponent
, there's a button that increments the count state. TheMemoizedChildComponent
receives a prop with the current count, and it will only re-render when the count changes. -
If you open the browser's console and click the "Increment Count" button, you'll notice that
ChildComponent
is not re-rendering on each click, thanks toReact.memo
.
React.memo
is a helpful tool for optimizing functional components, especially when dealing with components that have expensive rendering logic or when you want to avoid unnecessary re-renders in your application. Keep in mind that React.memo
does a shallow comparison of props, so it works well when props are simple values or references that don't change often. If your props contain complex objects or functions, you might need to use other techniques for more fine-grained control over when a component should re-render.