| How to Test Custom React Hooks :👈 | 👉:React-memo-vs-useMemo-vs-useCallback |
How to Identify Unnecessary React Re-renders |
How to Identify Unnecessary React Re-renders
1. What Is a React Re-render?
A re-render occurs when React calls a component function again to calculate what its UI should look like.
Common reasons for re-renders include:
- A component's state changes.
- A parent component re-renders, causing its children to be rendered again by default.
- A component receives different props.
- A component consumes a Context value that changes.
- An external store or subscription used by the component reports a change.
For example:
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
console.log("Counter rendered");
return (
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
);
}
export default Counter;
Every time the button updates the count, React renders the component again to calculate the updated UI.
Important: A re-render is not automatically a performance problem. React is designed to render components frequently when needed. The goal is to identify re-renders that cause measurable performance problems or unnecessary work.
2. What Is an Unnecessary Re-render?
An unnecessary re-render occurs when a component renders again without needing to produce a meaningfully different result, and that extra work has no useful purpose.
For example, suppose a page contains a counter and a large product list. Clicking the counter updates its value, but the product list does not depend on the counter.
If the product list performs expensive calculations on every render, the counter update may trigger unnecessary work in the list.
import { useState } from "react";
function ProductList({ products }) {
console.log("ProductList rendered");
return (
<ul>
{products.map(product => (
<li key={product.id}>{product.name}</li>
))}
</ul>
);
}
function Dashboard() {
const [count, setCount] = useState(0);
const products = [
{ id: 1, name: "Laptop" },
{ id: 2, name: "Keyboard" },
{ id: 3, name: "Mouse" }
];
return (
<div>
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
<ProductList products={products} />
</div>
);
}
Whenever the counter changes, Dashboard renders again. It also creates a new array for products, so ProductList receives a different array reference.
Even though the product data has the same contents, the new reference can prevent a memoized child from skipping its render.
3. First Understand What Actually Causes Re-renders
Before optimizing, distinguish between the common causes.
| Cause | Example | What to Investigate |
|---|---|---|
| Local state update | setCount(count + 1) |
Is the state owned by the correct component? |
| Parent re-render | A dashboard updates its counter. | Are unrelated children doing expensive work? |
| New object or array reference | products = [{ id: 1 }] |
Is the value recreated on every render? |
| New function reference | onClick={() => save()} |
Does the child need a stable callback reference? |
| Context update | A theme or user Context value changes. | Are too many components consuming the same Context? |
| External store update | A subscribed store publishes a change. | Is the component subscribed to more data than it needs? |
A component can re-render even when its props have not changed. For example, its own state or a Context value may have changed.
4. Method 1: Use React Developer Tools
React Developer Tools is one of the best starting points for investigating component rendering behavior.
It provides two useful panels:
- Components: Inspect the component tree, props, state, and Context values.
- Profiler: Record rendering activity and identify components that render during an interaction.
Steps to Investigate Re-renders
- Install the React Developer Tools browser extension.
- Open your React application in the browser.
- Open browser Developer Tools.
- Select the Profiler tab.
- Start recording.
- Perform the interaction that appears slow, such as typing into a search field or changing a filter.
- Stop recording.
- Inspect the recorded commits and components that rendered.
- Check which components took the most time and whether unrelated components rendered.
The Profiler can help you distinguish between a large number of inexpensive renders and a smaller number of expensive renders.
Important: A component appearing in a profile does not automatically mean its render was unnecessary. Check what changed and whether the work contributed to the visible result.
5. Method 2: Use Highlight Updates in React DevTools
React Developer Tools provides a setting to highlight component updates visually while interacting with the application.
To investigate:
- Open React Developer Tools.
- Open the settings.
- Find the option for highlighting component updates, if available in your installed version.
- Enable it.
- Interact with your application and observe which regions update.
This is useful for identifying components that repeatedly update when you interact with an unrelated part of the page.
For example, if typing one character into a search box causes a large product grid to update, investigate whether the grid needs to render for every keystroke.
Visual highlighting is an initial clue, not proof of a performance problem. Use the Profiler to investigate further.
6. Method 3: Add Console Logs Temporarily
For a quick investigation, add a log at the beginning of a component.
function ProductList({ products }) {
console.log("ProductList rendered");
return (
<ul>
{products.map(product => (
<li key={product.id}>{product.name}</li>
))}
</ul>
);
}
Now interact with the page and observe when the message appears.
If the list renders whenever an unrelated counter changes, check whether that work is expensive and whether it can be avoided.
Be careful: Console logs show when the component function executes, not how much time React spends committing changes to the DOM.
Also, React Strict Mode can cause additional component calls in development to help reveal bugs. Do not assume every extra console message represents a production re-render.
7. Method 4: Use React Profiler in Code
React provides a Profiler component that measures rendering performance for a section of the component tree.
Example:
import { Profiler } from "react";
function onRender(
id,
phase,
actualDuration,
baseDuration,
startTime,
commitTime
) {
console.log({
id,
phase,
actualDuration,
baseDuration,
startTime,
commitTime
});
}
function App() {
return (
<Profiler id="ProductList" onRender={onRender}>
<ProductList />
</Profiler>
);
}
In this example:
ididentifies the Profiler boundary.phaseindicates whether the measured update is a mount or an update.actualDurationmeasures the time spent rendering the profiled tree for the current update.baseDurationestimates the time the tree would take to render without skipping work through memoization.startTimeindicates when React began rendering the update.commitTimeidentifies the commit associated with the measurement.
Important: These measurements help evaluate rendering work, but they do not directly tell you whether a render was unnecessary. Compare them with the interaction being investigated.
Profiling support and overhead vary by build. For detailed React Profiler measurements, use an appropriate development profiling setup or a profiling-enabled production build.
8. Example: Identify Unnecessary Child Re-renders
Consider this example in which updating a counter also causes a product list to render.
Before Optimization
import { useState } from "react";
function ProductList({ products }) {
console.log("ProductList rendered");
return (
<ul>
{products.map(product => (
<li key={product.id}>{product.name}</li>
))}
</ul>
);
}
function Dashboard() {
const [count, setCount] = useState(0);
const products = [
{ id: 1, name: "Laptop" },
{ id: 2, name: "Keyboard" },
{ id: 3, name: "Mouse" }
];
return (
<div>
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
<ProductList products={products} />
</div>
);
}
What happens?
- The user clicks the counter button.
- The counter state changes.
Dashboardrenders again.- A new
productsarray is created. ProductListrenders again.
If rendering the list is expensive, this extra work may affect performance.
After Optimization: Use React.memo and a Stable Array
import { memo, useState } from "react";
const products = [
{ id: 1, name: "Laptop" },
{ id: 2, name: "Keyboard" },
{ id: 3, name: "Mouse" }
];
const ProductList = memo(function ProductList({ products }) {
console.log("ProductList rendered");
return (
<ul>
{products.map(product => (
<li key={product.id}>{product.name}</li>
))}
</ul>
);
});
function Dashboard() {
const [count, setCount] = useState(0);
return (
<div>
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
<ProductList products={products} />
</div>
);
}
export default Dashboard;
Now:
- The product array is created outside the component, so its reference remains stable.
React.memocan skip renderingProductListwhen its props remain unchanged.- Updating the counter no longer needs to render the product list, assuming the list's own state, Context, and other relevant conditions have not changed.
Note: 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 or a consumed Context value changes.
9. Method 5: Identify Unstable Function References
Functions declared inside a component are recreated when that component renders.
This can matter when a function is passed to a memoized child.
Problem Example
import { memo, useState } from "react";
const SaveButton = memo(function SaveButton({ onSave }) {
console.log("SaveButton rendered");
return (
<button onClick={onSave}>
Save
</button>
);
});
function Editor() {
const [count, setCount] = useState(0);
const handleSave = () => {
console.log("Saved");
};
return (
<div>
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
<SaveButton onSave={handleSave} />
</div>
);
}
When Editor renders, it creates a new handleSave function. Because the function reference changes, React.memo sees a changed prop and renders SaveButton again.
Possible Solution: useCallback
import { memo, useCallback, useState } from "react";
const SaveButton = memo(function SaveButton({ onSave }) {
console.log("SaveButton rendered");
return (
<button onClick={onSave}>
Save
</button>
);
});
function Editor() {
const [count, setCount] = useState(0);
const handleSave = useCallback(() => {
console.log("Saved");
}, []);
return (
<div>
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
<SaveButton onSave={handleSave} />
</div>
);
}
export default Editor;
Now handleSave has a stable reference between renders while its dependencies remain unchanged, so the memoized child can skip rendering when its other props also remain unchanged.
Use useCallback when stable function identity provides a meaningful benefit. It is not necessary for every event handler.
10. Method 6: Identify Unstable Object and Array Props
Objects and arrays created during rendering have new references, even when their contents are identical.
For example:
function Dashboard() {
const [count, setCount] = useState(0);
const settings = {
theme: "dark",
language: "en"
};
return (
<>
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
<SettingsPanel settings={settings} />
</>
);
}
If SettingsPanel is memoized, it can still render whenever Dashboard renders because settings is a new object.
If the settings are constant, move them outside the component:
const settings = {
theme: "dark",
language: "en"
};
function Dashboard() {
const [count, setCount] = useState(0);
return (
<>
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
<SettingsPanel settings={settings} />
</>
);
}
For values that genuinely depend on component state or props, consider whether a stable reference is necessary. You can use useMemo when caching the value is beneficial.
11. Method 7: Identify Context-Related Re-renders
When a Context provider receives a different value, components that consume that Context may render again.
Consider this example:
import { createContext, useContext, useState } from "react";
const UserContext = createContext(null);
function UserName() {
const user = useContext(UserContext);
console.log("UserName rendered");
return <p>User: {user.name}</p>;
}
function Dashboard() {
const [count, setCount] = useState(0);
const user = {
name: "Sam"
};
return (
<UserContext value={user}>
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
<UserName />
</UserContext>
);
}
This example uses the React 19 Context provider syntax. In React 18 and earlier, use <UserContext.Provider value={user}>.
Whenever Dashboard renders, it creates a new user object. That changes the provider value by reference, so consumers may render again even though the name is still "Sam".
Potential improvements include:
- Keep genuinely constant values outside the component.
- Memoize provider values when their object identity causes unnecessary updates.
- Split unrelated state into separate Contexts when consumers need different parts of the state.
- Keep state close to the components that need it.
Important: Memoizing a provider value does not prevent consumers from rendering when the actual Context value changes. Also, wrapping a Context consumer in React.memo does not block updates to the Context it consumes.
12. Method 8: Check Whether State Is Stored Too High in the Component Tree
State placement can affect how many components render when a value changes.
Suppose a page contains a search box and several unrelated sections. If the search state is stored in the page's root component, every update to that state can cause the root component and its children to render.
Instead, move the state into the smallest component that needs it when that makes the component structure simpler.
Example:
import { useState } from "react";
function SearchPanel() {
const [query, setQuery] = useState("");
return (
<div>
<input
value={query}
onChange={event => setQuery(event.target.value)}
placeholder="Search products"
/>
<p>Search query: {query}</p>
</div>
);
}
function Dashboard() {
return (
<div>
<h1>Dashboard</h1>
<SearchPanel />
<SalesSummary />
<Notifications />
</div>
);
}
Now typing into the search box updates the state in SearchPanel, rather than requiring the dashboard's own state to change.
This helps isolate the update. If the parent does not otherwise render, the unrelated dashboard sections do not need to render just because the search query changed.
13. How to Distinguish Re-rendering from DOM Updates
One of the most important concepts in React performance debugging is that a component re-render does not necessarily mean the browser DOM changes.
There are several stages to understand:
- Render: React calls components to calculate the next UI description.
- Reconciliation: React compares the new result with the previous result.
- Commit: React applies the necessary changes and performs relevant commit-phase work.
- Browser rendering: The browser may perform layout, paint, and compositing as needed.
For example, a component might render again and return the same text. React can determine that no DOM update is needed.
Therefore, do not assume that a component render always causes a DOM update or a visible flicker.
Use the React Profiler to measure React rendering work. Use browser performance tools when you need to investigate layout, painting, long JavaScript tasks, or other browser-level bottlenecks.
14. A Step-by-Step Debugging Workflow
Follow this process when you suspect unnecessary re-renders in a real application.
- Reproduce the problem: Identify the exact interaction that causes slowness.
- Record a profile: Use React Developer Tools Profiler to capture the interaction.
- Find expensive components: Look for components with high rendering durations or frequent updates.
- Inspect the component tree: Identify whether state, props, Context, or subscriptions cause the update.
- Check prop references: Look for newly created objects, arrays, and functions.
- Check state placement: Determine whether state can live closer to the components that need it.
- Apply one change: For example, stabilize a prop, split a Context, or move state.
- Profile again: Confirm that the change reduces the work without breaking functionality.
- Measure the user experience: Confirm that the interaction is actually faster or smoother.
Optimization should be driven by measurements, not simply by counting renders.
15. Common Mistakes When Debugging Re-renders
Mistake 1: Assuming Every Re-render Is Bad
Re-rendering is a normal part of React. Avoid optimizing components that are inexpensive to render and do not create a measurable performance problem.
Mistake 2: Adding React.memo Everywhere
React.memo can reduce rendering work when props remain unchanged, but it adds comparison work and does not prevent updates caused by a component's own state or consumed Context.
Mistake 3: Using useCallback for Every Function
useCallback is useful when a stable function reference prevents meaningful work, but it is not automatically beneficial for every function.
Mistake 4: Ignoring Object and Array References
A memoized component can render again because an object or array prop was recreated during the parent render.
Mistake 5: Trusting Development Console Counts
Strict Mode can introduce additional renders and Effect setup-and-cleanup cycles in development. Evaluate behavior in context and use profiling rather than relying only on console messages.
Mistake 6: Confusing Re-renders with Effect Executions
An Effect can run because its dependencies changed, even when the component's rendering cost is small. Conversely, a component can render without its Effect running again if the dependencies have not changed.
Mistake 7: Optimizing Without Measuring
A technique that reduces the number of renders may not improve the actual user experience. Measure the rendering cost before and after making changes.
16. Quick Reference: Which Tool Should You Use?
| Tool or Technique | Purpose |
|---|---|
| Console logs | Quickly see when a component function executes. |
| React DevTools Components | Inspect component props, state, and Context. |
| React DevTools Profiler | Identify rendering activity and expensive components. |
| Highlight updates | Visually inspect regions that update during interactions. |
<Profiler> |
Collect React rendering measurements programmatically. |
| Browser Performance panel | Investigate JavaScript execution, layout, paint, and other browser performance problems. |
17. Best Practices
- Start with React Developer Tools Profiler rather than optimizing by guesswork.
- Identify the component and interaction responsible for expensive work.
- Keep state as close as practical to the components that use it.
- Avoid recreating object and array props unnecessarily when stable references matter.
- Use
React.memowhen skipping child renders provides a measurable benefit. - Use
useMemofor expensive calculations when caching helps. - Use
useCallbackwhen stable function identity helps avoid meaningful work. - Split Contexts when unrelated consumers need independent updates.
- Remember that component re-renders do not necessarily cause DOM mutations.
- Profile again after each significant optimization.
18. React Interview Questions and Answers
Q1. What causes a React component to re-render?
Common causes include local state changes, parent re-renders, changed props, Context updates, and updates from external stores or subscriptions.
Q2. Does a parent re-render always cause its children to re-render?
By default, React normally calls child component functions again when their parent renders. A child wrapped in React.memo may skip rendering if its props remain equal and it has no other update requiring a render.
Q3. How do you identify unnecessary re-renders?
Use React Developer Tools Profiler to record interactions, inspect which components rendered, and investigate their rendering cost and update causes. Console logs can also help during initial debugging.
Q4. What is the purpose of React.memo?
React.memo lets React skip rendering a component when its props are unchanged according to its comparison behavior. It does not prevent the component from rendering because of its own state or consumed Context changes.
Q5. How can useCallback help with re-renders?
useCallback can preserve a function reference between renders while its dependencies remain unchanged. This can help a memoized child skip rendering when the callback is its only changing prop.
Q6. Why can object props cause unnecessary re-renders?
Objects created during rendering have new references. Since memoization normally compares props by reference for objects, the child may be considered to have changed props even if the object contains identical values.
Q7. What is the difference between a re-render and a DOM update?
A re-render means React recalculates the component's output. A DOM update occurs only when React determines that a change to the rendered output needs to be committed to the DOM.
Q8. Should React.memo be used for every component?
No. Use it when profiling shows that skipping renders provides a meaningful benefit. Unnecessary memoization can add complexity without improving performance.
19. Final Summary
- A re-render is a normal part of React's update process.
- An unnecessary re-render is worth addressing when it causes avoidable work or a measurable performance problem.
- React Developer Tools Profiler is a key tool for identifying expensive rendering activity.
- Console logs and visual highlighting are useful initial debugging techniques.
- Unstable function, object, and array references can prevent memoized children from skipping renders.
- Context updates and state placement can affect how widely updates propagate through the component tree.
React.memo,useMemo, anduseCallbackcan help when used appropriately.- Component re-renders do not necessarily result in DOM changes.
- Always measure performance before and after optimizing.
The key principle: Find the component doing unnecessary work, understand why it renders, and use profiling to confirm whether the fix improves performance. Do not try to eliminate every re-render.
| How to Test Custom React Hooks :👈 | 👉:React-memo-vs-useMemo-vs-useCallback |
Comments and Discussion