Memoizing Components with React.memo
React applications are built using reusable components. Whenever a component's state changes or its parent renders again, React may execute that component to calculate the updated user interface. Sometimes a child component receives exactly the same props as before, so rendering it again may perform unnecessary work.
React.memo is a React API that lets you create a memoized version of a component. When its props remain unchanged according to the default comparison, React can skip rendering that component during a parent update.
1. What Is Memoization?
Memoization is an optimization technique that reuses a previously calculated result when the relevant inputs have not changed. Instead of repeating the same work, a program can reuse the previous result when appropriate.
In React, React.memo applies this idea to function components. It allows React to reuse the previous rendered result for a component when its props have not changed, instead of rendering the component again because its parent rendered.
2. Syntax of React.memo
React.memo receives a component and returns a memoized component. You can import memo from React and wrap the function component.
import { memo } from "react";
const MyComponent = memo(function MyComponent(props) {
return <h2>Hello, {props.name}</h2>;
});
export default MyComponent;
In this syntax:
- memo: The React API used to memoize a component.
- MyComponent: The function component being optimized.
- props: The data received by the component.
- export default: Makes the component available for import elsewhere.
3. Example Without React.memo
First, create a parent component with a counter and a child component displaying a student's name. Clicking the counter button changes the parent's state, causing the parent to render again.
import { useState } from "react";
function StudentCard({ name }) {
console.log("StudentCard rendered");
return (
<div>
<h3>Student Name: {name}</h3>
<p>Welcome to CIIT Training Institute.
How It Works
- StudentApp renders and displays Counter: 0.
- StudentCard displays the name Samadhan.
- The user clicks Increase Counter.
- setCount updates the parent's state.
- StudentApp renders again with the updated count.
- StudentCard can render again even though its name prop is unchanged.
Expected Console Behavior
Initial render:
StudentApp rendered
StudentCard rendered
After a counter click:
StudentApp rendered
StudentCard rendered
Development Strict Mode can cause extra render calls while React checks components for unintended side effects. Therefore, the number of console messages may be higher in development.
4. Example With React.memo
Now import memo from React and wrap StudentCard. The name prop is a string and remains unchanged when only the counter updates. React.memo can therefore skip rendering StudentCard during that parent update.
import { memo, useState } from "react";
const StudentCard = memo(function StudentCard({ name }) {
console.log("StudentCard rendered");
return (
<div>
<h3>Student Name: {name}</h3>
<p>Welcome to CIIT Training Institute.</p>
</div>
);
});
function StudentApp() {
const [count, setCount] = useState(0);
console.log("StudentApp rendered");
return (
<div>
<h2>Counter: {count}</h2>
<button onClick={() => setCount(c => c + 1)}>
Increase Counter
</button>
<StudentCard name="Samadhan" />
</div>
);
}
export default StudentApp;
Expected Behavior
Initial render: StudentApp and StudentCard render.
After clicking Increase Counter: StudentApp renders again, but StudentCard can skip rendering.
The counter updates normally, and the student's name remains visible.
5. How Does React.memo Compare Props?
By default, React.memo compares each prop in the previous render with the corresponding prop in the next render using Object.is. If all props compare equal, React can skip rendering the memoized component when the update comes from its parent.
| Prop Type | Example | Comparison Behavior |
|---|---|---|
| String | "Samadhan" | Same string value compares equal. |
| Number | 25 | Same number compares equal. |
| Boolean | true | Same boolean value compares equal. |
| Object | {`{ name: "Samadhan" }`} | Different object references compare unequal, even if their contents look the same. |
| Function | onClick handler | A newly created function generally has a different reference. |
6. Problem: New Object Props
Consider a parent that creates a new object every time it renders. Even when the object contains the same student name, its reference is new. React.memo therefore treats that prop as changed.
import { memo, useState } from "react";
const StudentCard = memo(function StudentCard({ student }) {
console.log("StudentCard rendered");
return <h3>Student: {student.name}</h3>;
});
function StudentObject() {
const [count, setCount] = useState(0);
const student = { name: "Samiksha" };
return (
<div>
<button onClick={() => setCount(c => c + 1)}>
Counter: {count}
</button>
<StudentCard student={student} />
</div>
);
}
export default StudentObject;
Why Does the Child Render Again?
- The parent renders and creates a student object.
- The counter changes and the parent renders again.
- A new student object is created.
- The new object reference differs from the previous reference.
- React.memo detects a changed prop, so it cannot skip the child based on prop equality.
Improved Example: Pass a Primitive Prop
import { memo, useState } from "react";
const StudentCard = memo(function StudentCard({ name }) {
console.log("StudentCard rendered");
return <h3>Student: {name}</h3>;
});
function StudentObject() {
const [count, setCount] = useState(0);
return (
<div>
<button onClick={() => setCount(c => c + 1)}>
Counter: {count}
</button>
<StudentCard name="Samiksha" />
</div>
);
}
export default StudentObject;
Here, the name prop remains the same string. When only the counter changes, React.memo can skip the child render because the prop has not changed.
7. Using React.memo with Multiple Props
A memoized component can receive multiple props. React compares each prop separately. If any prop changes, the component will generally render again in response to the parent update.
import { memo, useState } from "react";
const StudentProfile = memo(function StudentProfile({ name, course }) {
console.log("StudentProfile rendered");
return (
<div>
<h3>{name}</h3>
<p>Course: {course}</p>
</div>
);
});
function StudentApp() {
const [count, setCount] = useState(0);
const [course, setCourse] = useState("React");
return (
<div>
<button onClick={() => setCount(c => c + 1)}>
Counter: {count}
</button>
<button onClick={() => setCourse("Node.js")}>
Change Course
</button>
<StudentProfile
name="Samadhan"
course={course}
/>
</div>
);
}
export default StudentApp;
Expected Behavior
Click Counter: StudentProfile can skip rendering because its props remain unchanged.
Click Change Course: StudentProfile renders again because the course prop changes.
The displayed course changes from React to Node.js.
8. When Should You Use React.memo?
- When a component renders frequently with the same props.
- When rendering the component involves meaningful work.
- When a parent updates for reasons unrelated to the child.
- When profiling shows that repeated child renders are a bottleneck.
- When the component receives stable primitive props or intentionally stable references.
9. When Should You Avoid React.memo?
- When the component is very small and inexpensive to render.
- When its props change on almost every render.
- When memoization makes the code unnecessarily complicated.
- When no measurable performance benefit is expected.
10. Custom Comparison Function
React.memo also accepts an optional second argument: a comparison function. It receives the previous props and next props. Return true when the component can reuse its previous rendered result, and false when it should render again.
import { memo } from "react";
const StudentCard = memo(
function StudentCard({ student }) {
return <h3>Student: {student.name}</h3>;
},
(previousProps, nextProps) => {
return previousProps.student.name ===
nextProps.student.name;
}
);
export default StudentCard;
In this example, the comparison function checks only the student's name. If the name remains the same, it returns true and allows React to skip rendering based on this comparison.
11. Common Mistakes
- Assuming React.memo stops all component renders.
- Passing newly created objects and functions to memoized components without considering their references.
- Using memoization on every component without measuring performance.
- Assuming equal object contents always mean equal object references.
- Using a custom comparison function that ignores important props.
- Expecting React.memo to prevent updates from local state or consumed context.
12. Practice Tasks
Task 1: Basic Memoization
Create a Parent component with a counter and a StudentCard child. Observe the console before and after wrapping StudentCard with React.memo.
Task 2: Multiple Props
Create a memoized profile component that accepts name, course, and city. Change one prop at a time and observe which updates cause the child to render.
Task 3: Object References
Pass an object to a memoized child. Change the parent's counter and explain why a newly created object can cause another render.
Task 4: Custom Comparison
Create a comparison function for a student profile. Ensure that every prop affecting the UI is compared correctly.
Task 5: Explain the Concept
In your own words, explain memoization, shallow prop comparison, and two situations in which React.memo may improve performance.
Summary
React.memo creates a memoized version of a function component and can skip rendering it when its props compare equal using React's default shallow comparison. It is useful when a child repeatedly receives unchanged props while its parent renders for another reason. Newly created object and function references can prevent the optimization, while changed props, local state, and consumed context can still lead to renders. A custom comparison function is available but must be written carefully. At CIIT Training Institute, practice memoization with parent-child components and use profiling to confirm that an optimization provides a real benefit.