Sub topic 1
Why Components Re-render and Why It Sometimes Matters
Prerequisites
This chapter assumes you already know the following:
- Function components, props, and state in React.
- The
useState,useEffect,useMemo, anduseCallbackhooks at a basic level. - How to read a small JSX component and follow what it renders.
You do not need to know anything about the React Compiler yet. This chapter sets up the problem the compiler solves. Later chapters cover the compiler itself.
What a render is
A render is React calling your component function to find out what the UI should look like. The function returns a description of the UI (React elements). React compares that description with the previous one and updates the DOM only where something changed.
Two points are easy to mix up:
- Rendering is not the same as touching the DOM. A component can render and produce exactly the same output as last time. In that case React makes no DOM changes.
- Rendering is only the calling of your function. Your function still runs, and any work inside it is paid for, even when nothing visible changes.
So a "wasted" render costs CPU time but does not cause visible flicker or DOM writes. That is why re-renders are often harmless, and why they only sometimes matter.
What triggers a re-render
A component re-renders for one of three reasons.
- Its own state changes. Calling a state setter with a new value schedules a render of that component.
- Its parent re-renders. By default, React re-renders every child of a component that rendered. It does this even if the props passed to the child did not change.
- A context it reads changes. Any component that calls
useContexton a context re-renders when that context's value changes.
The second reason surprises many developers. Props changing is not required for a child to re-render. The following example shows it.
import { useState } from 'react';
function Child() {
console.log('Child rendered');
return <p>I take no props.</p>;
}
export function Parent() {
const [count, setCount] = useState(0);
return (
<>
<button onClick={() => setCount(count + 1)}>Clicked {count}</button>
<Child />
</>
);
}Each click updates count in Parent. Parent re-renders, and so does Child, even though Child has no props and its output never changes. You will see "Child rendered" in the console on every click.
How the cascade spreads
A re-render starts at the component that owns the changed state and moves down the tree. React does not move up. Siblings and ancestors of the component that owns the state are not re-rendered because of it.
In the diagram, state lives in Dashboard. When it changes, Dashboard, Chart, and Table re-render. App, Sidebar, and Menu do not.
This is why placing state close to where it is used is a cheap and effective optimization. A small state variable in a leaf component re-renders only that leaf. The same variable in the root re-renders the whole app.
When re-rendering matters
Most re-renders are fast. React is designed so that calling many small functions is cheap. You should not treat every re-render as a bug. A re-render is worth caring about in these situations.
- Expensive computation during render. Sorting or filtering a large array, parsing data, or running a heavy calculation inside the component body repeats on every render.
- Large subtrees. A parent that renders hundreds or thousands of children pays for every child on every update, even when only one thing changed.
- Frequent updates. State that changes on every keystroke, mouse move, or animation frame turns a small cost into a visible slowdown.
- Downstream side effects. Effects and memoized values whose dependencies change on every render run more often than intended.
The last item leads to the main idea of this chapter: unstable references.
Unstable references
JavaScript compares objects, arrays, and functions by reference, not by contents. Two objects with identical fields are still different values if they were created separately.
const a = { id: 1 };
const b = { id: 1 };
console.log(a === b); // false
console.log(a === a); // trueA component body runs again on every render. Any object, array, or function created inside it is therefore a new value each time, even when its contents are the same.
function Toolbar({ onSave }) {
const style = { padding: 8 }; // new object every render
const handleClick = () => onSave('draft'); // new function every render
return <Button style={style} onClick={handleClick} />;
}Every time Toolbar renders, style and handleClick have new identities. Any code that compares them by reference sees a change that is not real. This matters in three places:
- Memoized children. A child wrapped in
React.memoskips rendering when its props are shallowly equal to the last props. A new function or object prop makes the comparison fail, so the memo does nothing. - Hook dependency arrays.
useEffect,useMemo, anduseCallbackcompare each dependency withObject.is. A dependency that is recreated every render makes the effect re-run or the cache miss on every render. - Context values. A provider that passes a new object as
valueon each render re-renders every consumer.
An unstable reference is not a problem by itself. It is a problem when something downstream treats a change in identity as a reason to do real work.
A concrete example
The next component filters a list as the user types. It also keeps a selected ID in state.
import { useState } from 'react';
function Row({ item, onSelect }) {
console.log('Row rendered:', item.id);
return <li onClick={() => onSelect(item.id)}>{item.name}</li>;
}
export function List({ items }) {
const [query, setQuery] = useState('');
const [selectedId, setSelectedId] = useState(null);
const visible = items.filter((i) => i.name.includes(query));
return (
<>
<input value={query} onChange={(e) => setQuery(e.target.value)} />
<p>Selected: {selectedId}</p>
<ul>
{visible.map((item) => (
<Row key={item.id} item={item} onSelect={setSelectedId} />
))}
</ul>
</>
);
}Consider what happens when the user clicks a row and selectedId changes.
Listre-renders because its own state changed.items.filter(...)runs again, althoughitemsandqueryare the same.- Every
Rowre-renders, because their parent rendered.
Here the onSelect prop is setSelectedId, which React guarantees is stable. The item objects come from items, so they are stable too. Even so, Row re-renders, because without React.memo the stable props do not stop it. With 10 rows nobody notices. With 5,000 rows and a filter running on every keystroke, typing becomes sluggish.
The cause is not a mistake in the code. It is the default behavior: render the whole subtree and let React find the differences.
Measuring before you optimize
Do not optimize on a hunch. Check that re-rendering is actually your problem first.
- React DevTools Profiler. Record an interaction, then look at the flame chart. It shows which components rendered, how long each took, and why. Turn on "Record why each component rendered while profiling" in the Profiler settings to see whether a render came from state, props, or a parent.
- Highlight updates. In the Components tab settings, enable "Highlight updates when components render". Components flash when they render, which makes cascades easy to see.
- Production builds. Development builds are much slower than production builds. Measure with a production build before you decide something is too slow.
A useful rule is to fix the cause before you add a cache. Move state down, split a component, or pass children instead of rendering a heavy subtree next to changing state. Reach for memoization when those options do not fit.
The standard remedies
React gives you three manual tools to stop work that did not need to happen. The next chapter covers them in detail. In short:
| Tool | What it caches | What it avoids |
|---|---|---|
| `React.memo` | A component's rendered output, keyed on its props | Re-rendering a child when its props are shallowly equal |
| `useMemo` | A computed value, keyed on a dependency array | Repeating an expensive calculation, or creating a new object or array identity |
| `useCallback` | A function, keyed on a dependency array | Creating a new function identity on every render |
These tools work together. React.memo only helps if the props it receives are stable, and useMemo and useCallback are how you keep them stable. Writing all three correctly, with accurate dependency arrays, is the cost that motivates the React Compiler.
Common misunderstandings
- "A re-render means the DOM was rebuilt." It does not. React updates the DOM only for real differences.
- "A child re-renders only when its props change." Without
React.memo, a child re-renders whenever its parent does. - "Every re-render is a performance bug." Most are cheap. Only repeated heavy work and large trees need attention.
- "State changes re-render the whole app." Only the component that owns the state and its descendants re-render.
- "
useCallbackmakes a function faster." It only keeps the same function identity. It does not speed up the function. It pays off only when something compares that identity.
Summary of the model
Keep this working model in mind for the rest of the tutorial:
- State changes, parent renders, and context changes cause renders.
- A render runs your function top to bottom and moves down to the children.
- New objects, arrays, and functions created during render have new identities each time.
- Reference comparisons in
React.memo, dependency arrays, and context turn those new identities into extra work. - Memoization breaks that chain, but doing it by hand takes care and adds code.
Exercise
In the Parent and Child example earlier in this chapter, Child takes no props. Why does it still re-render when the button is clicked, and what is the smallest change that stops it?
Show answer
Clicking the button changes count, so Parent re-renders. By default React re-renders all children of a component that rendered, whether or not their props changed. The smallest fix is to wrap Child in React.memo. With no props, the shallow comparison always finds them equal, so React skips Child. Moving the counter and button into their own component, so Child is not its descendant, also works.
Exercise
A component creates const options = { sort: 'asc' }; in its body and passes it to a useEffect dependency array. The effect fetches data. What goes wrong, and how can you fix it without useMemo?
Show answer
options is a new object on every render, so Object.is sees a changed dependency each time. The effect runs, and re-fetches, after every render. Without useMemo, move the constant outside the component so it is created once, or depend on the primitive value instead, for example [sort] with sort as a string.