Sub topic 1
Why components re-render
Prerequisites
This chapter assumes you already know:
- Function components and JSX.
- The
useStateanduseEffecthooks. - How props and
childrenpass between components. - That JavaScript objects, arrays and functions are reference values.
You do not need to know React.memo, useMemo or useCallback. Later chapters cover them. This chapter explains the mechanism they all depend on: what makes React call your component function again.
Rendering is calling your function
In React, "rendering" means calling a component function to find out what it should display. The function returns a description of the UI, made of React elements. React compares that description with the previous one and updates the DOM only where something changed.
Two ideas are easy to mix up:
- Render: React calls your component and gets back elements. This is plain JavaScript work. It can be cheap or costly.
- Commit: React applies the differences to the DOM. If the output is the same as last time, the commit does nothing.
A component can render without touching the DOM. That is why a re-render is not automatically a performance problem. It becomes one only when the render work itself is slow, or when it happens far more often than needed.
What triggers a render
A component renders again for one of three reasons.
- Its own state changed. Calling a state setter with a new value schedules a render of that component.
- Its parent rendered. When a component renders, React renders every child element it returns, recursively. This is the default, and it happens even if the child's props are identical.
- A context it reads changed. Components that call
useContextrender again when the provider's value changes.
The second reason causes most unwanted renders. Props changing is not a trigger by itself. A child re-renders because its parent re-rendered, and new props usually arrive as a side effect.
import { useState } from 'react';
function Child({ label }) {
console.log('render Child');
return <p>{label}</p>;
}
export function Parent() {
const [count, setCount] = useState(0);
console.log('render Parent');
return (
<>
<button onClick={() => setCount(count + 1)}>Clicked {count}</button>
<Child label="Always the same" />
</>
);
}Click the button and the console prints both render Parent and render Child. The label prop never changes, but Child still renders because Parent did.
The render cycle
The sequence below is what happens after a state update.
Step D is the one to remember. By default React does not check whether a child needs to render. It just calls it. Tools such as React.memo add a check at that point, which later chapters cover.
The render tree
Consider a tree of components.
If Page owns the state that changed, then Page, Sidebar and Content render. App and Header do not, because rendering flows downward only. A state update never re-renders a parent or a sibling directly.
This gives a useful rule: the cost of a state update is the cost of the component that owns the state plus everything below it. Keeping state high in the tree makes updates touch more components.
Props alone do not cause renders
A common misconception is that React re-renders a child "because its props changed." Check this against the example above. If the parent does not render, the child does not render, whatever its props would have been. Props can only change when the parent renders and passes new values.
The reverse also matters. Identical props do not stop a render. Without memo, a child with no props at all still renders whenever its parent does.
Renders must be pure
React may call your component function more than once, and in development StrictMode deliberately renders twice to expose problems. For this reason, render must be a pure calculation: same props, state and context in, same elements out.
Avoid these inside the render body:
- Mutating variables declared outside the component.
- Mutating props or state objects.
- Starting network requests, timers or subscriptions. Use
useEffectfor these.
import { useState } from 'react';
let renderCount = 0; // module-level, shared by every instance
export function Bad() {
renderCount += 1; // side effect during render
const [n, setN] = useState(0);
return <button onClick={() => setN(n + 1)}>{n} / {renderCount}</button>;
}The renderCount value drifts under StrictMode and under concurrent rendering, where React can start a render and throw it away. Logging with console.log to watch renders is fine for learning, but do not build behavior on counting them.
Bailing out when state does not change
If you call a state setter with a value equal to the current one, React may skip the render. It compares with Object.is.
import { useState } from 'react';
export function Toggle() {
const [on, setOn] = useState(false);
console.log('render Toggle');
return (
<>
<button onClick={() => setOn(false)}>Set false</button>
<span>{String(on)}</span>
</>
);
}While on is already false, clicking the button does not change anything. React usually skips rendering the children and does not commit. There is one catch: React can still call the Toggle function once more before it decides to bail out. So you may see one extra log line, but no children render and the DOM is not touched.
Objects behave differently. Setting state to a new object with the same contents counts as a change, because the reference is new.
import { useState } from 'react';
export function Profile() {
const [user, setUser] = useState({ name: 'Ada' });
console.log('render Profile');
return (
<button onClick={() => setUser({ name: 'Ada' })}>
Reset {user.name}
</button>
);
}Every click renders Profile because { name: 'Ada' } is a new object each time. The next chapters build on this point about references.
Several updates, one render
React batches state updates made in the same event. Three setter calls in one click handler produce one render, not three.
import { useState } from 'react';
export function Counter() {
const [a, setA] = useState(0);
const [b, setB] = useState(0);
console.log('render Counter');
function handleClick() {
setA(a + 1);
setB(b + 1);
setA((prev) => prev + 1);
}
return <button onClick={handleClick}>{a} / {b}</button>;
}One click logs render Counter once. Note that a ends at 1, not 2, after the first click. The first setA(a + 1) queues "set to 1", then the updater function receives that queued 1 and returns 2. The final queued value wins, so a becomes 2 on the next render. Inside the handler, the variable a still holds the value from the render that created the handler.
Batching applies to updates in timeouts, promises and native event handlers too.
Context triggers renders from a distance
Context bypasses the parent-to-child path. Any component that calls useContext(SomeContext) renders when the provider's value changes, even if its parent did not render.
import { createContext, useContext, useState } from 'react';
const ThemeContext = createContext('light');
function ThemedLabel() {
const theme = useContext(ThemeContext);
console.log('render ThemedLabel');
return <p>Theme: {theme}</p>;
}
export function App() {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={theme}>
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Toggle
</button>
<ThemedLabel />
</ThemeContext.Provider>
);
}Here ThemedLabel renders because App renders and because its context value changed. If ThemedLabel were deeper and wrapped in a component that skips renders, the context change would still reach it. A later chapter covers this interaction with memo.
Keys and identity
React decides whether to keep or reset a component's state by its position in the tree and its key. If the type and position match the previous render, React keeps the existing instance and its state. If they differ, React unmounts the old one and mounts a new one.
This matters for performance in two ways:
- A changing
keyforces a full remount, which is more expensive than a re-render. - Defining a component inside another component creates a new function type on every render. React sees a different type each time and remounts the whole subtree.
export function Page() {
// Broken: Inner is a new function on every render of Page,
// so its state is lost and its DOM is rebuilt each time.
function Inner() {
return <input />;
}
return <Inner />;
}Define components at module level instead.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| Assuming a child renders only when its props change | Unneeded renders go unnoticed | Remember that a parent render renders its children |
| Treating every re-render as a bug | Time spent optimizing cheap renders | Measure first, which the next chapter covers |
| Putting side effects in the render body | Duplicate effects under StrictMode | Move them into `useEffect` or event handlers |
| Defining a component inside another | State resets and the DOM is rebuilt on every render | Move the definition to module level |
| Using index as `key` in a reorderable list | State attaches to the wrong item | Use a stable id |
| Reading a state variable right after its setter | Stale value in the same handler | Use the updater form or compute the next value first |
Where this leads
The rest of the tutorial rests on this model.
- If a render is cheap, leave it alone.
- If it is costly, first ask whether the state can live lower in the tree.
- Otherwise, add a check that lets React skip a child whose inputs are the same as last time. That check compares values, which requires understanding referential equality. That is the subject of the chapter after the Profiler.
Exercise
In the tree App → Page → (Sidebar, Content), a button inside Content calls its own useState setter. Which components render? Then the state is moved up to App instead. Which components render now, assuming no memo anywhere?
Show answer
With the state in Content, only Content renders, because updates flow down from the owner and Content has no children here. With the state in App, App renders and so do all its descendants: Header (if present), Page, Sidebar and Content. Moving state up widens the set of components that render.
Exercise
A component calls setUser({ name: 'Ada' }) when the current state is already { name: 'Ada' }. Does React skip the render? Why or why not?
Show answer
No. React compares the new and old state with Object.is. The new object literal is a different reference from the old one, so React treats it as a change and renders again. A primitive such as false, set while the state is already false, would be treated as equal and React would bail out.
Exercise
A handler runs setA(a + 1) and then setA((prev) => prev + 1), where a is 0 when the handler was created. How many renders happen, and what is the value of a afterward?
Show answer
One render, because React batches both updates from the same event. The value of a is 2: the first call queues 1, and the updater then receives 1 and returns 2.