In React, memo is a Higher-Order Component (HOC) that allows you to optimize functional components by memoizing the result. This means that a component will only re-render when its props change, which can lead to performance improvements in certain scenarios.
Basic Usage of React.memo
Here's how to use React.memo:
import React from 'react';
// A simple functional component
const MyComponent = ({ value }) => {
console.log('Rendering MyComponent');
return <div>{value}</div>;
};
// Wrapping the component with React.memo
const MemoizedComponent = React.memo(MyComponent);
export default MemoizedComponent;
How React.memo Works
-
Shallow Comparison: By default, React.memo performs a shallow comparison of any props. If the props are the same as they were during the last render, the memoized component does not re-render.
-
Custom Comparison Function: You can pass a custom comparison function as the second argument to React.memo. This function receives the previous props and the next props and should return true if they are equal (in which case the component will not re-render) or false if they are not.
Example with Custom Comparison
import React from 'react';
const MyComponent = ({ value }) => {
console.log('Rendering MyComponent');
return <div>{value}</div>;
};
// Custom comparison function
const areEqual = (prevProps, nextProps) => {
return prevProps.value === nextProps.value;
};
// Using React.memo with a custom comparison function
const MemoizedComponent = React.memo(MyComponent, areEqual);
export default MemoizedComponent;
When to Use React.memo
-
Performance Optimization: Use React.memo when you have functional components that receive complex objects or large data structures as props and do not need to re-render on every parent component render.
-
Static Props: It can be particularly useful for child components that receive props that don’t change frequently.
Example in a Parent Component
Here's a complete example demonstrating its use in a parent component:
import React, { useState } from 'react';
import MemoizedComponent from './MemoizedComponent';
const ParentComponent = () => {
const [count, setCount] = useState(0);
const [value, setValue] = useState('Hello');
return (
<div>
<button onClick={() => setCount(count + 1)}>Increment Count</button>
<button onClick={() => setValue(value === 'Hello' ? 'Goodbye' : 'Hello')}>Change Value</button>
<div>Count: {count}</div>
<MemoizedComponent value={value} />
</div>
);
};
export default ParentComponent;
Summary
- Purpose:
React.memo is an optimization technique for functional components to prevent unnecessary re-renders.
- Shallow Comparison: Default behavior is to shallowly compare props.
- Custom Logic: You can provide a custom comparison function for more complex data.
By using React.memo, you can improve the performance of your React application, especially with frequently re-rendering components.