React.memo – Complete Notes
1. Introduction to React.memo
React.memo is a higher-order component (HOC) in React that helps optimize the performance of functional components. It prevents unnecessary re-rendering by memorizing the rendered result of a component and reusing it when its props have not changed.
Normally, when a parent component re-renders, its child components may also re-render. By wrapping a child component with React.memo, React can skip rendering that child when its props remain unchanged.
Syntax:
const MemoizedComponent = React.memo(Component);
2. Why Do We Use React.memo?
In React applications, unnecessary re-renders can affect performance, especially when components are complex or appear many times on a page. React.memo helps reduce these unnecessary renders when the component receives the same props.
- Improves performance in suitable components.
- Prevents unnecessary child component re-renders caused by parent re-renders.
- Reduces repeated rendering work when props remain unchanged.
- Is useful for expensive components and large lists.
- Helps optimize reusable UI components.
3. Basic Example of React.memo
Consider a parent component that contains a child component. Whenever the parent updates, the child may render again even if the child's props have not changed.
Example without React.memo:
import React, { useState } from "react";
function Child({ name }) {
console.log("Child rendered");
return <h2>Hello, {name}!</h2>;
}
function Parent() {
const [count, setCount] = useState(0);
return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => setCount(count + 1)}>
Increase Count
</button>
<Child name="Rahul" />
</div>
);
}
export default Parent;
Explanation: When the button is clicked, the parent's state changes and the parent re-renders. The Child component may also render again even though the name prop remains "Rahul".
4. Using React.memo to Optimize a Component
We can wrap the Child component with React.memo to avoid re-rendering it when its props have not changed.
import React, { useState } from "react";
const Child = React.memo(function Child({ name }) {
console.log("Child rendered");
return <h2>Hello, {name}!</h2>;
});
function Parent() {
const [count, setCount] = useState(0);
return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => setCount(count + 1)}>
Increase Count
</button>
<Child name="Rahul" />
</div>
);
}
export default Parent;
Explanation: The parent still re-renders when the count changes, but React.memo can skip rendering Child because its name prop remains unchanged.
5. How React.memo Works
React.memo performs a shallow comparison of the previous props and the new props. If the props are equal, React can reuse the previous rendered result instead of rendering the component again.
- The parent component renders.
- The child receives its props.
- The parent updates and renders again.
- React.memo compares the previous and new props.
- If the props are shallowly equal, React can skip the child's render.
- If a prop changes, React renders the child again.
Important: React.memo is a performance optimization, not a guarantee that a component will never render again. A memoized component can still render when its own state changes, when a consumed context value changes, or when React otherwise needs to render it.
6. React.memo with Multiple Props
React.memo works with components that receive multiple props. The component can skip rendering when all the props remain shallowly equal.
import React from "react";
const UserProfile = React.memo(function UserProfile({ name, age }) {
console.log("UserProfile rendered");
return (
<div>
<h2>Name: {name}</h2>
<p>Age: {age}</p>
</div>
);
});
export default UserProfile;
Example usage:
<UserProfile name="Amit" age={25} />
If both props remain unchanged between renders, React.memo can skip rendering the component. If either prop changes, the component can render again.
7. React.memo with Objects and Arrays
React.memo uses shallow comparison, so objects and arrays are compared by reference rather than by checking every nested value. Creating a new object or array on every parent render can cause a memoized child to render again.
Example:
const UserCard = React.memo(function UserCard({ user }) {
console.log("UserCard rendered");
return <h2>{user.name}</h2>;
});
function Parent() {
return <UserCard user={{ name: "Amit" }} />;
}
In this example, a new object is created whenever Parent renders. Because the object reference changes, React.memo treats the prop as changed.
Improved example using useMemo:
import React, { useMemo } from "react";
function Parent() {
const user = useMemo(() => ({ name: "Amit" }), []);
return <UserCard user={user} />;
}
useMemo can preserve the object reference between renders when its dependencies remain unchanged. Use it when profiling shows that stable references are beneficial.
8. React.memo with Functions and useCallback
Functions are also compared by reference. If a parent creates a new callback function during each render and passes it to a memoized child, that changed function reference may cause the child to render again.
Example:
import React, { useCallback } from "react";
const Button = React.memo(function Button({ onClick }) {
console.log("Button rendered");
return <button onClick={onClick}>Click Me</button>;
});
function Parent() {
const handleClick = useCallback(() => {
console.log("Button clicked");
}, []);
return <Button onClick={handleClick} />;
}
export default Parent;
Here, useCallback can preserve the function reference while its dependencies remain unchanged. This allows React.memo to skip rendering Button when its other props are also unchanged.
9. React.memo with a Custom Comparison Function
React.memo accepts an optional second argument, a custom comparison function. It lets developers decide whether the previous and new props are equivalent for rendering purposes.
Syntax:
const MemoizedComponent = React.memo(
Component,
arePropsEqual
);
The comparison function receives the previous props and the new props. It must return true when the component can safely reuse its previous render, and false when it should render again.
Example:
import React from "react";
function Profile({ name, age }) {
return (
<div>
<h2>{name}</h2>
<p>Age: {age}</p>
</div>
);
}
const MemoizedProfile = React.memo(
Profile,
(previousProps, nextProps) => {
return (
previousProps.name === nextProps.name &&
previousProps.age === nextProps.age
);
}
);
export default MemoizedProfile;
Explanation: The custom function returns true when the name and age are equal, allowing React to skip rendering. Custom comparisons should be used carefully because deep or expensive comparisons can cost more than rendering the component itself.
10. Difference Between React.memo, useMemo, and useCallback
| Feature |
React.memo |
useMemo |
useCallback |
| Type |
Higher-order component |
React Hook |
React Hook |
| Purpose |
Can skip rendering a component when its props are unchanged |
Can cache a calculated value |
Can cache a function reference |
| Used for |
Component rendering optimization |
Expensive calculations or stable values |
Stable callback references |
| Returns |
A memoized component |
A cached value |
A cached function |
| Example |
React.memo(Profile) |
useMemo(() => a + b, [a, b]) |
useCallback(fn, [dependency]) |
11. When Should You Use React.memo?
- When a component renders frequently with the same props.
- When rendering a component is computationally expensive.
- When rendering many reusable items in a list.
- When a parent updates often but a particular child does not need new output.
- When performance profiling shows that avoiding the render provides a measurable benefit.
12. When Should You Avoid React.memo?
- When a component is small and inexpensive to render.
- When its props change on nearly every render.
- When memoization adds complexity without measurable improvement.
- When a custom comparison function is more expensive than rendering.
- When you are using it everywhere without measuring performance.
13. Advantages of React.memo
- Can reduce unnecessary rendering work.
- Can improve responsiveness in performance-sensitive components.
- Supports shallow comparison of props by default.
- Works well with useMemo and useCallback when stable references are useful.
- Can help optimize complex interfaces and repeated list items.
14. Limitations of React.memo
- It does not prevent renders caused by a component's own state updates.
- It does not prevent renders caused by changes to consumed context values.
- New object, array, and function references can cause a render.
- Memoization introduces comparison overhead.
- It does not automatically make an entire application faster.
15. React.memo in a List Example
React.memo can be useful when a parent renders a list of items and only a small number of items change.
import React, { useState } from "react";
const TodoItem = React.memo(function TodoItem({ todo }) {
console.log("Rendered:", todo.text);
return <li>{todo.text}</li>;
});
function TodoList() {
const [todos, setTodos] = useState([
{ id: 1, text: "Learn React.memo" },
{ id: 2, text: "Practice React Hooks" }
]);
return (
<div>
<button onClick={() =>
setTodos(items => [
...items,
{ id: Date.now(), text: "New Task" }
])
}>
Add Task
</button>
<ul>
{todos.map(todo => (
<TodoItem key={todo.id} todo={todo} />
))}
</ul>
</div>
);
}
export default TodoList;
Explanation: When a new task is added, existing todo objects retain their references. React.memo can therefore skip rendering existing TodoItem components whose props are unchanged and render the new item. This assumes the existing todo objects are not recreated during the update.
16. Common Mistakes When Using React.memo
- Expecting zero renders: React.memo is an optimization, not a guarantee that a component never renders.
- Creating new objects: New object references may cause a memoized component to render again.
- Creating new functions: Inline callbacks can change prop references on each parent render.
- Ignoring state and context: A component can still render when its own state or consumed context changes.
- Overusing memoization: Adding memoization everywhere can make code harder to understand without improving performance.
- Incorrect custom comparison: Returning true when props affect the output can cause stale UI or outdated callback behavior.
17. Best Practices for React.memo
- Use React DevTools Profiler to identify unnecessary or expensive renders.
- Apply React.memo to components that benefit from skipping renders.
- Keep props simple and stable where practical.
- Use useMemo for values and useCallback for functions only when they provide a benefit.
- Ensure custom comparison functions account for every prop that affects rendering and behavior.
- Measure performance before and after optimization.
- Keep component code readable and maintainable.
18. Practical Mini Project: Product Card Optimization
Objective: Create a product card that does not need to re-render when an unrelated counter in the parent changes.
import React, { useState } from "react";
const ProductCard = React.memo(function ProductCard({ name, price }) {
console.log("ProductCard rendered");
return (
<div>
<h2>{name}</h2>
<p>Price: ₹{price}</p>
</div>
);
});
function App() {
const [count, setCount] = useState(0);
return (
<div>
<h1>Counter: {count}</h1>
<button onClick={() => setCount(c => c + 1)}>
Increase Counter
</button>
<ProductCard name="Wireless Mouse" price={799} />
</div>
);
}
export default App;
Expected result: Clicking Increase Counter updates the counter. ProductCard can skip rendering because its name and price props remain unchanged. The parent still renders, but the memoized product card can reuse its previous output.
19. Interview Questions and Answers
Q1. What is React.memo?
Answer: React.memo is a higher-order component that can skip re-rendering a functional component when its props are shallowly equal to their previous values.
Q2. Does React.memo prevent every re-render?
Answer: No. A component may still render when its own state changes, a consumed context value changes, or React otherwise needs to render it.
Q3. What comparison does React.memo use by default?
Answer: It performs a shallow comparison of the previous and new props.
Q4. Can React.memo work with multiple props?
Answer: Yes. React.memo compares all props shallowly. If the props are unchanged, React can skip rendering the component.
Q5. What is the difference between React.memo and useMemo?
Answer: React.memo memoizes a component's rendering based on its props, while useMemo caches the result of a calculation between renders when its dependencies remain unchanged.
Q6. What is the difference between React.memo and useCallback?
Answer: React.memo can skip rendering a component when its props are unchanged, while useCallback caches a function reference between renders.
Q7. Can React.memo compare object props?
Answer: Yes, but the default comparison checks object references rather than deeply comparing their contents.
Q8. What is the purpose of a custom comparison function?
Answer: It allows developers to define when the previous and new props are equivalent enough to reuse the previous render.
Q9. Should React.memo be used on every component?
Answer: No. Use it when it provides a measurable performance benefit.
Q10. How can you check whether React.memo is helping?
Answer: Use React DevTools Profiler and compare rendering behavior and performance before and after the optimization.
20. Summary
React.memo is a useful React performance optimization for functional components that frequently receive unchanged props. It performs a shallow comparison by default and can skip rendering when the props are equal. It works particularly well when combined thoughtfully with useMemo and useCallback, but it should be used based on actual performance needs rather than applied everywhere.
21. Learn React JS with JustAcademy
Learn React components, props, state, Hooks, performance optimization, and modern front-end development through structured training and practical projects.
JustAcademy React JS Training
Interested in learning more about the course? Register for a demo session using the link below.
Register for React JS Course Demo