React.memo is a performance optimization technique in React.
It prevents unnecessary component re-rendering when props do not change.
Why React.memo Is Important
Normally, when a parent component re-renders, all child components also re-render.
Even if the child props are exactly the same.
This can reduce performance in large applications.
[grid]
Prevent Unnecessary Re-render
Improve React Performance
Optimize Child Components
Reduce Extra Rendering
[/grid]
Problem Without React.memo
Every time the count changes:
- Parent component re-renders
- Child component also re-renders
- Even if props are unchanged
App.jsx
[code theme="dark"]
import React, { useState } from "react";
import Child from "./Child";
function App() {
const [count, setCount] = useState(0);
return (
React.memo Example
Count: {count}
);
}
export default App;
[/code]
Child.jsx
[code theme="dark"]
function Child({ name }) {
console.log("Child component rendered");
return (
Child Component {name}
);
}
export default Child;
[/code]
Here:
- Clicking increment updates count
- Parent component re-renders
- Child component also re-renders
- Even though name prop is same
Solution Using React.memo
React.memo memorizes the component result.
If props are unchanged, React skips re-rendering.
Child.jsx
[code theme="dark"]
import React from "react";
function Child({ name }) {
console.log("Child component rendered");
return (
Child Component {name}
);
}
export default React.memo(Child);
[/code]
Now:
- Parent component still re-renders
- But Child component does not re-render
- Because props are unchanged
[grid]
Optimized Child Rendering
React Performance Optimization
Memoized React Component
Prevent Extra Re-renders
[/grid]
How React.memo Works
React.memo performs a shallow comparison of props.
If previous props and new props are same:
[code theme="dark"]
No Re-render
[/code]
If props change:
[code theme="dark"]
Component Re-renders
[/code]
Simple Flow
[code theme="dark"]
Parent Re-render
↓
Check Child Props
↓
Same Props
→ Skip Re-render
Different Props
→ Re-render Child
[/code]
Best Use Cases
- Large component trees
- Reusable UI components
- Dashboard applications
- Heavy rendering components
- Lists and cards
Important Notes
- React.memo works only with props
- Useful for performance optimization
- Not needed for every component
- Works best with stable props
When React.memo Will Not Help
If props change every render:
[code theme="dark"]
[/code]
A new object is created every time.
So React.memo cannot prevent re-rendering.
Difference Between Normal Component and React.memo
|
Feature
|
Normal Component
|
React.memo
|
|
Re-renders with parent
|
Yes
|
No (if props same)
|
|
Performance Optimization
|
No
|
Yes
|
Final Understanding
[code theme="dark"]
React.memo
Prevent unnecessary
component re-rendering
when props are unchanged
[/code]