Sub topic 7
Common causes of unnecessary re-renders
This chapter assumes you can build function components with props, state, and hooks, and that you have recorded a session in the React DevTools Profiler and read its "why did this render?" information. Here you will learn the usual reasons a component renders when its output has not changed, and how to recognize each one in a profile.
What "unnecessary" means
A render is unnecessary when React calls your component function and gets the same output as last time. React then compares the new output with the old output and changes nothing in the DOM. The commit does no visible work, but the render still cost CPU time.
One re-render costs little. The cost matters when the component is expensive, when many instances re-render together, or when it happens on every keystroke or scroll event. Profile first, and fix only the renders that show up as slow.
The default rule: parents re-render children
When a component's state changes, React re-renders that component and every component it returns, whether or not their props changed. Props are not checked unless you opt in with React.memo.
The next diagram shows one state change in App spreading down the tree.
This is expected behavior, not a bug. Most of the causes below are variations on it.
Cause 1: state held too high
State that only one subtree uses, but that lives in a shared parent, re-renders everything under that parent. Typing in a search box that lives in the page component re-renders the whole page.
In the Profiler's flamegraph this appears as a wide tree where nearly every bar is colored, and the "why did this render?" panel reads "The parent component rendered" for most of them. Only the component that owns the state shows "Hooks changed."
The fix is to move the state down into the smallest component that needs it. The previous chapter covered that technique. It is the first thing to try, because it removes the render without adding any memoization code.
Cause 2: new object, array, and function identities
React compares props by identity with Object.is, not by content. Every render of a parent creates new object literals, array literals, and inline functions. A memoized child sees a different reference and re-renders.
import { memo, useState } from "react";
const Chart = memo(function Chart({ options, onZoom }) {
console.log("Chart rendered");
return <canvas />;
});
export function Panel() {
const [count, setCount] = useState(0);
return (
<>
<button onClick={() => setCount(count + 1)}>Clicked {count}</button>
{/* options and onZoom are new on every render, so memo never helps */}
<Chart options={{ smooth: true }} onZoom={() => console.log("zoom")} />
</>
);
}Chart is wrapped in memo, yet it logs on every click. The options object and the onZoom arrow function are created fresh each time Panel runs. The Profiler shows this as "Props changed: options, onZoom" for a component whose props look identical when you print them.
There are three ways to fix it:
- Move constants outside the component, so they are created once.
- Wrap values in
useMemoand callbacks inuseCallback, with correct dependencies. - Pass primitives (strings, numbers, booleans) instead of objects when you can.
import { memo, useCallback, useState } from "react";
const CHART_OPTIONS = { smooth: true };
const Chart = memo(function Chart({ options, onZoom }) {
console.log("Chart rendered");
return <canvas />;
});
export function Panel() {
const [count, setCount] = useState(0);
const handleZoom = useCallback(() => console.log("zoom"), []);
return (
<>
<button onClick={() => setCount(count + 1)}>Clicked {count}</button>
<Chart options={CHART_OPTIONS} onZoom={handleZoom} />
</>
);
}Now Chart renders once on mount and stays quiet when the count changes.
Cause 3: context value changes
Every component that calls useContext(SomeContext) re-renders whenever the provider's value changes by identity. React.memo does not block this, because the update comes from context, not from props.
A common mistake creates a new value object in each provider render:
import { createContext, useState } from "react";
export const SettingsContext = createContext(null);
export function SettingsProvider({ children }) {
const [theme, setTheme] = useState("light");
const [locale, setLocale] = useState("en");
// New object on every render: all consumers re-render every time.
return (
<SettingsContext.Provider value={{ theme, setTheme, locale, setLocale }}>
{children}
</SettingsContext.Provider>
);
}Two problems exist here. First, the object is recreated whenever SettingsProvider renders, for example when its own parent renders. Second, even with a stable object, changing locale notifies components that only read theme.
Common remedies:
- Memoize the value with
useMemoso it changes only when its contents change. - Split one large context into several smaller ones, for example one for theme and one for locale.
- Separate rarely changing values (such as setter functions) from frequently changing ones.
In the Profiler, a context-triggered render appears as "Context changed" for the consumer.
Cause 4: the children prop is not stable
Passing JSX as children can prevent re-renders, because the element objects are created by the parent of the stateful component, not by the stateful component itself.
import { useState } from "react";
function ColorPicker({ children }) {
const [color, setColor] = useState("red");
return (
<div style={{ color }}>
<input value={color} onChange={(e) => setColor(e.target.value)} />
{children}
</div>
);
}
export function Page() {
return (
<ColorPicker>
<ExpensiveTree />
</ColorPicker>
);
}When color changes, ColorPicker re-renders, but children is the same element object that Page created earlier. React sees the same reference and skips ExpensiveTree. The reverse also holds: if Page itself re-renders, it builds new children and ExpensiveTree renders again.
This pattern is a free alternative to memoization. It fails only when whoever creates the children element re-renders often.
Cause 5: unstable keys and remounting
A key tells React which list item is which. Two key mistakes cause more than a re-render, because they cause a remount, where React destroys the component, its state, and its DOM nodes, and builds them again.
- Using
Math.random()or a fresh id as a key makes every item look new on every render. - Using the array index as a key in a list that is reordered, filtered, or inserted into makes React match the wrong items and re-render or reset them.
A related mistake is defining a component inside another component:
export function Parent({ items }) {
// Wrong: Row is a new function (a new component type) on every Parent render.
const Row = ({ item }) => <li>{item.name}</li>;
return (
<ul>
{items.map((item) => (
<Row key={item.id} item={item} />
))}
</ul>
);
}React compares component types by identity. Each render of Parent creates a new Row, so React unmounts every old row and mounts a new one. In the Profiler, the phase shows "mount" for components you expected to "update," and local state inside the rows is lost. Move Row to module scope to fix this.
Cause 6: effects that set state
An effect that sets state on every run can trigger extra renders. The sequence is: render, commit, effect, state update, render again.
import { useEffect, useState } from "react";
export function Total({ items }) {
const [total, setTotal] = useState(0);
// Extra render on every change to items.
useEffect(() => {
setTotal(items.reduce((sum, item) => sum + item.price, 0));
}, [items]);
return <p>Total: {total}</p>;
}The first render shows a stale total, the effect runs, and a second render shows the correct one. Compute the value during rendering instead:
export function Total({ items }) {
const total = items.reduce((sum, item) => sum + item.price, 0);
return <p>Total: {total}</p>;
}If the calculation is costly, wrap it in useMemo. Values you can derive from props and state should not be stored in state.
Cause 7: Strict Mode in development
In development, StrictMode renders each component twice to help find impure render functions. This can look like an unnecessary re-render in logs, but it does not happen in a production build. Do not try to optimize it away. The chapter on development and production builds explains why dev timings differ.
Matching symptoms to causes
| What the Profiler shows | Likely cause |
|---|---|
| "The parent component rendered" on many components | State too high, or no `memo` boundary |
| "Props changed" on a memoized component, with equal-looking props | New object, array, or function identity |
| "Context changed" on many consumers | Unmemoized or overly broad context value |
| Phase is "mount" when you expected "update" | Unstable key or component defined inside a component |
| Two commits for one user action | Effect that sets state derived from props |
Do not memoize everything
Memoization has costs: extra code, dependency arrays that can be wrong, and a comparison on every render. If the memoized component is cheap, the comparison can cost about as much as the render it saves. Fix the structure first (move state down, pass children), then add memo, useMemo, and useCallback where the Profiler shows a real cost.
Exercise
A component Row is wrapped in React.memo. Its parent passes style={{ color: "red" }}. The Profiler says "Props changed: style" on every parent render, although the style never differs. Give two ways to fix it.
Show answer
The inline object is a new reference each render, so the shallow comparison fails. Either define the object once outside the component (const rowStyle = { color: "red" }) or create it with useMemo(() => ({ color: "red" }), []). Passing a primitive such as a color string as a prop also works.
Exercise
A page has a ThemeContext provider whose value is { theme, toggle } created inline in the provider component. Consumers wrapped in React.memo still re-render whenever the provider's parent renders. Why, and what do you change?
Show answer
Context updates bypass memo. The inline object has a new identity on every provider render, so every consumer is notified. Wrap the value in useMemo with [theme, toggle] as dependencies, and make toggle stable with useCallback. Splitting rarely changing values into a separate context also helps.