What is React.memo?
React.memo is a higher-order component in React that helps prevent unnecessary re-renders of a functional component when its props have not changed.
Normally, when a parent component re-renders, its child components may also re-render. React.memo can skip a child component's re-render if its props are unchanged.
Syntax
const MemoizedComponent = React.memo(Component);
Here:
-
React.memo()receives a component. - It returns a memoized version of that component.
- React compares the previous props with the new props using shallow comparison by default.
Why Do We Use React.memo?
We use React.memo to:
- Avoid unnecessary child component re-renders.
- Improve performance in suitable situations.
- Optimize components that render frequently with unchanged props.
- Reduce repeated rendering work in large applications.
Example Without React.memo
import { useState } from "react";
function Child() {
console.log("Child rendered");
return <h2>Hello from Child</h2>;
}
function App() {
const [count, setCount] = useState(0);
return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => setCount(count + 1)}>
Increase
</button>
<Child />
</div>
);
}
export default App;
How does it work?
Whenever the button is clicked, the count state changes and App re-renders.
The Child component also re-renders, even though it does not receive any props and its output has not changed.
Example With React.memo
import { useState, memo } from "react";
const Child = memo(function Child() {
console.log("Child rendered");
return <h2>Hello from Child</h2>;
});
function App() {
const [count, setCount] = useState(0);
return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => setCount(count + 1)}>
Increase
</button>
<Child />
</div>
);
}
export default App;
How does it work?
- Initially, the
Childcomponent renders. - Clicking Increase updates the parent's
count. - The parent re-renders.
- React checks the child's props.
- Since the child has no props to compare, React can skip its re-render.
Note: React may still re-render a memoized component when its own state or a context value it uses changes. Memoization is an optimization, not a guarantee.
React.memo vs useMemo
| Feature | Purpose |
|---|---|
React.memo |
Memoizes a component based on its props |
useMemo |
Memoizes a calculated value |
Conclusion
React.memo is useful for optimizing functional components by skipping re-renders when their props remain unchanged. It is most helpful when a component renders frequently and its rendering work is significant. It should be used when it provides a meaningful performance benefit, rather than automatically wrapping every component.
Top comments (0)