React.memo
is a higher-order component (HOC) that helps optimize the performance of React components by preventing unnecessary re-renders. It is used to memoize functional components, which means React will skip re-rendering the component if its props haven't changed. This is particularly useful for performance optimization in large React applications where re-rendering may be costly.
How React.memo
Works
React.memo
works by performing a shallow comparison of the props of the component. If the props are the same as the previous render, React will skip rendering the component and use the result from the previous render instead. This can significantly reduce the number of re-renders and improve performance, especially when rendering large lists or expensive components.
Syntax
const MemoizedComponent = React.memo(Component);
Where:
-
Component
is the functional component you want to memoize. -
MemoizedComponent
is the new memoized version of the component.
Example: Basic Usage of React.memo
Let's look at a simple example of how React.memo
can be used:
import React, { useState } from 'react';
const ChildComponent = React.memo(({ name }) => {
console.log("Child component re-rendered");
return <div>Hello, {name}!</div>;
});
function App() {
const [name, setName] = useState('John');
const [count, setCount] = useState(0);
return (
<div>
<ChildComponent name={name} />
<button onClick={() => setName('Doe')}>Change Name</button>
<button onClick={() => setCount(count + 1)}>Increment Count</button>
<p>Count: {count}</p>
</div>
);
}
export default App;
Explanation:
-
ChildComponent
is wrapped inReact.memo
. It only re-renders when thename
prop changes. -
App
has two pieces of state:name
andcount
. Clicking the "Increment Count" button doesn't change thename
prop, so theChildComponent
doesn't re-render when thecount
state is updated. - If you click "Change Name", the
name
prop changes, causingChildComponent
to re-render.
Output:
- When you click the "Increment Count" button, the
ChildComponent
will not re-render, but it will log "Child component re-rendered" when thename
prop changes.
Custom Comparison with React.memo
By default, React.memo
performs a shallow comparison of props, but you can provide a custom comparison function if you need more control over how props are compared.
The custom comparison function should return true
if the component should not re-render and false
if it should.
Example: Custom Comparison Function
const ChildComponent = React.memo(
({ name, age }) => {
console.log("Child component re-rendered");
return <div>Hello, {name}, {age}!</div>;
},
(prevProps, nextProps) => {
// Custom comparison: only re-render if name changes
return prevProps.name === nextProps.name;
}
);
function App() {
const [name, setName] = useState('John');
const [age, setAge] = useState(30);
return (
<div>
<ChildComponent name={name} age={age} />
<button onClick={() => setName('Doe')}>Change Name</button>
<button onClick={() => setAge(age + 1)}>Increment Age</button>
</div>
);
}
In this example, the ChildComponent
will only re-render when the name
prop changes, even if the age
prop changes, thanks to the custom comparison function.
When to Use React.memo
-
Performance Optimization: If you have functional components that receive props and do not change often,
React.memo
can help avoid unnecessary renders. -
List Rendering: For large lists where only a few elements change,
React.memo
can be very useful. For example, when rendering a list of items, memoizing each list item component will prevent re-renders of unchanged items. -
Expensive Components: If a component has expensive rendering logic (e.g., complex calculations or rendering heavy data), using
React.memo
can improve the overall performance by avoiding unnecessary recalculations.
When Not to Use React.memo
-
Small Components: For small components with few props, using
React.memo
may add overhead without providing a significant performance boost. -
Changing Props Frequently: If a component receives props that change frequently,
React.memo
may not offer much benefit since the component will re-render anyway. - Complex Comparison Logic: Custom comparison logic can be more expensive than just allowing the component to re-render normally. Only use it when necessary.
Conclusion
React.memo
is a simple yet powerful optimization tool in React for preventing unnecessary re-renders of functional components. By memoizing components and using shallow prop comparison (or a custom comparison function), React can skip rendering those components when their props haven't changed, leading to performance improvements, especially in large or complex applications.
Top comments (1)
Hello you got telegram or Twitter so we can talk on a deal