Avoiding Unnecessary Re-Renders in React
In React, components render again when React needs to calculate an updated user interface. This behavior is necessary for displaying new state and props. However, some components may perform additional rendering work even when their displayed information has not changed.
Avoiding unnecessary re-renders means reducing work that does not contribute to a meaningful UI update. It is especially useful in applications containing large component trees, complex calculations, long lists, or expensive UI components.
1. What Is an Unnecessary Re-Render?
An unnecessary re-render is a render that performs avoidable work without providing a useful change to the user interface. For example, a parent component may update a counter while a separate child component displays fixed information.
If that child is expensive to render and does not need new information, rendering it again may waste resources. In a small application, the cost may be negligible. In a larger application, repeated work can affect responsiveness.
2. Example Without Optimization
Consider a parent component with a counter and a child component displaying a student's name. Clicking the counter button updates the parent's state. The child can also render again, even though its name has not changed.
import { useState } from "react";
function StudentInfo({ name }) {
console.log("StudentInfo rendered");
return (
<div>
<h3>Student Name: {name}</h3>
<p>Welcome to CIIT Training Institute.</p>
</div>
);
}
function Parent() {
const [count, setCount] = useState(0);
console.log("Parent rendered");
return (
<div>
<h2>Counter: {count}</h2>
<button onClick={() => setCount(c => c + 1)}>
Increase Counter
</button>
<StudentInfo name="Samiksha" />
</div>
);
}
export default Parent;
How This Example Works
- React renders the Parent component for the initial display.
- Parent displays the counter and renders StudentInfo.
- StudentInfo displays the name Samiksha.
- The user clicks Increase Counter.
- The counter state changes, causing Parent to render again.
- StudentInfo may also render again, although its name remains the same.
Expected Console Behavior
Initial render:
Parent rendered
StudentInfo rendered
After clicking the counter button:
Parent rendered
StudentInfo rendered
The exact number of console messages can differ in development when React Strict Mode is enabled. The important concept is that a normal parent update can also cause its child to render again.
3. Solution One: Use React.memo
React.memo is a higher-order component that can skip rendering a function component when its props are unchanged according to React's default shallow comparison. It is useful when a component receives the same props repeatedly and its rendering work is worth avoiding.
import { memo, useState } from "react";
const StudentInfo = memo(function StudentInfo({ name }) {
console.log("StudentInfo rendered");
return (
<div>
<h3>Student Name: {name}</h3>
<p>Welcome to CIIT Training Institute.</p>
</div>
);
});
function Parent() {
const [count, setCount] = useState(0);
console.log("Parent rendered");
return (
<div>
<h2>Counter: {count}</h2>
<button onClick={() => setCount(c => c + 1)}>
Increase Counter
</button>
<StudentInfo name="Samiksha" />
</div>
);
}
export default Parent;
Expected Behavior After Optimization
Initial render: Parent and StudentInfo render.
After counter click: Parent renders again.
Because the name prop remains the same, React.memo can skip the StudentInfo render.
4. Solution Two: Keep State Close to Where It Is Used
State placement is one of the simplest ways to reduce unnecessary rendering. If a piece of state is required by only one small component, it usually does not need to live in a high-level parent.
When state is stored in a large parent, every update to that state causes the parent to render again. Its descendant components may also render. Moving the state into the component that needs it can reduce the number of components affected by that update.
Before: State in a Large Parent
import { useState } from "react";
function SearchBox({ query, setQuery }) {
return (
<input
value={query}
onChange={e => setQuery(e.target.value)}
placeholder="Search students"
/>
);
}
function StudentList() {
console.log("StudentList rendered");
return <p>Student list content</p>;
}
function Dashboard() {
const [query, setQuery] = useState("");
return (
<div>
<SearchBox query={query} setQuery={setQuery} />
<StudentList />
</div>
);
}
export default Dashboard;
Here, typing in the search field updates the query state in Dashboard. Dashboard renders again, and StudentList may render again even though it does not use the query.
After: Move the State into SearchBox
import { useState } from "react";
function SearchBox() {
const [query, setQuery] = useState("");
return (
<input
value={query}
onChange={e => setQuery(e.target.value)}
placeholder="Search students"
/>
);
}
function StudentList() {
console.log("StudentList rendered");
return <p>Student list content</p>;
}
function Dashboard() {
return (
<div>
<SearchBox />
<StudentList />
</div>
);
}
export default Dashboard;
This approach works when the query is needed only inside SearchBox. If another component needs the query, keep the state at the nearest common parent that needs to share it.
5. Solution Three: Avoid Unnecessary Object and Function Props
React.memo compares props shallowly. If a parent creates a new object or function during every render, the reference may be different even when the content looks the same.
Example: A New Object on Every Render
import { memo, useState } from "react";
const StudentCard = memo(function StudentCard({ student }) {
console.log("StudentCard rendered");
return <p>Student: {student.name}</p>;
});
function Parent() {
const [count, setCount] = useState(0);
const student = { name: "Samadhan" };
return (
<div>
<button onClick={() => setCount(c => c + 1)}>
Count: {count}
</button>
<StudentCard student={student} />
</div>
);
}
export default Parent;
Every time Parent renders, it creates a new student object. Although the name remains Samadhan, the object reference changes. Therefore, React.memo sees a changed prop and cannot skip StudentCard based on its default comparison.
Improved Version: Pass a Stable Primitive Prop
import { memo, useState } from "react";
const StudentCard = memo(function StudentCard({ name }) {
console.log("StudentCard rendered");
return <p>Student: {name}</p>;
});
function Parent() {
const [count, setCount] = useState(0);
return (
<div>
<button onClick={() => setCount(c => c + 1)}>
Count: {count}
</button>
<StudentCard name="Samadhan" />
</div>
);
}
export default Parent;
Sometimes objects or functions must be passed as props. In those cases, use tools such as useMemo or useCallback only when stable references are useful and the optimization is justified.
6. Solution Four: Use useMemo and useCallback When Appropriate
useMemo caches a calculation result between renders when its dependencies have not changed. useCallback caches a function definition between renders under the same dependency condition. They can be useful when expensive calculations or memoized child components would otherwise receive changing references.
import { memo, useCallback, useState } from "react";
const ActionButton = memo(function ActionButton({ onAction }) {
console.log("ActionButton rendered");
return (
<button onClick={onAction}>
Perform Action
</button>
);
});
function Parent() {
const [count, setCount] = useState(0);
const [message, setMessage] = useState("Ready");
const handleAction = useCallback(() => {
setMessage("Action completed");
}, []);
return (
<div>
<h2>Count: {count}</h2>
<p>Status: {message}</p>
<button onClick={() => setCount(c => c + 1)}>
Increase Counter
</button>
<ActionButton onAction={handleAction} />
</div>
);
}
export default Parent;
The handleAction function retains its reference between renders because it has no changing dependencies. As a result, ActionButton can skip rendering when the counter changes, provided its other props remain unchanged.
7. Use React Developer Tools Profiler
React Developer Tools includes a Profiler that helps you record rendering activity. It can help identify which components rendered, how much time rendering took, and whether an optimization made a measurable difference.
- Install or open React Developer Tools in your browser.
- Open the React DevTools Profiler tab.
- Start recording a user interaction.
- Perform the action that seems slow.
- Stop recording and inspect the component render information.
- Apply a targeted optimization and record again.
8. Comparison of Optimization Techniques
| Technique | Purpose | When It Helps |
|---|---|---|
| React.memo | Can skip rendering a component when props are unchanged. | Expensive child components receiving stable props. |
| Local State | Limits updates to the component that owns the state. | State is used by only one small part of the UI. |
| useMemo | Caches a calculation result. | Expensive calculations with unchanged dependencies. |
| useCallback | Caches a function definition. | Stable callback references are useful to memoized children. |
| Profiler | Measures rendering behavior. | Finding and verifying actual performance bottlenecks. |
9. Common Mistakes to Avoid
- Trying to prevent every re-render, including necessary updates.
- Using React.memo without considering the cost of rendering.
- Creating new object and function props for memoized children unnecessarily.
- Moving shared state too low when multiple components need it.
- Adding useMemo and useCallback everywhere without measuring.
- Assuming every re-render causes a DOM update.
- Ignoring React DevTools and optimizing based only on guesses.
10. Practice Tasks
Task 1: Identify Re-Renders
Create a Parent component with a counter and a StudentInfo child. Add console messages to both components and observe what happens when the counter changes.
Task 2: Apply React.memo
Wrap StudentInfo with React.memo. Click the counter button and compare the console output before and after the change.
Task 3: Move State
Create a dashboard with a search input and a student list. Move search state into the search component and observe whether the dashboard and list still render on every keystroke.
Task 4: Test Stable Props
Pass an object prop to a memoized component. Then replace it with a primitive prop and compare the rendering behavior.
Task 5: Profile an Application
Record a few interactions with React Developer Tools Profiler. Identify one component that performs avoidable work and explain how you would test a possible optimization.
Summary
Avoiding unnecessary re-renders helps React applications reduce avoidable work while preserving correct UI behavior. React.memo can skip rendering when props remain unchanged, and placing state close to the components that use it can prevent unrelated parts of the application from being affected by local updates. Stable object and function references may also help memoized components, while useMemo and useCallback are useful for specific, measured cases. React Developer Tools Profiler helps identify bottlenecks and verify improvements. At CIIT Training Institute, practice these techniques with real components and optimize only when there is a clear performance benefit.