Sub topic 3
What Triggers a Re-render
This chapter assumes you can write function components, use JSX, and call useState. It also assumes you know that a component is a function that returns a description of UI. The goal is to let you predict, for any component, whether React will call it again after something happens.
Rendering means calling your component
In React, "rendering" means React calls your component function to get a new description of the UI. It does not mean the browser repaints, and it does not mean the DOM changes. A component can render many times without touching the DOM, because React compares the new result with the previous one and only changes what differs. Later chapters cover that comparison. Here we only ask what causes the function call.
There are two kinds of render:
- The initial render, when the component first appears on screen.
- A re-render, when React calls the component again because something changed.
A re-render of a component always has one of three causes:
- The component's own state was updated.
- The component's parent re-rendered, and the parent returned this component again.
- A context the component reads has a new value.
Props changing is not a separate cause. Props can only change because a parent rendered and passed new values, which is cause 2. This distinction matters, because it explains why a child re-renders even when its props are identical.
Cause 1: a state update
Calling a state setter tells React that the component's state should be different. React schedules a re-render of that component and calls it again with the new state.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
console.log('Counter rendered with count', count);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}Each click calls setCount, which schedules a re-render. React then calls Counter again, and the console.log runs before any DOM update. The log line shows that the render phase happens first, and the DOM changes only afterward.
Setting the same value
If you call a setter with a value equal to the current state, React compares the two using Object.is. When they are equal, React usually skips re-rendering the children and does not commit any change. There is one quirk: React may still call your component function once more before it decides to bail out. This is why a stray console.log can appear once after a no-op update. It is not a bug, and it does not lead to a DOM update.
import { useState } from 'react';
function Toggle() {
const [on, setOn] = useState(false);
console.log('Toggle rendered', on);
return <button onClick={() => setOn(false)}>Set to false ({String(on)})</button>;
}After the first click, on is already false, so nothing changes visually and later clicks do not cause real work.
Mutation does not trigger anything
React only learns about a change when you call a setter. Changing an object or array in place does not notify React, and even when it does re-render for another reason, the in-place change breaks the Object.is comparison.
import { useState } from 'react';
function Cart() {
const [items, setItems] = useState(['apple']);
function addWrong() {
items.push('pear'); // mutates the existing array
setItems(items); // same reference, so React sees no change
}
function addRight() {
setItems([...items, 'pear']); // new array, new reference
}
return (
<>
<p>{items.join(', ')}</p>
<button onClick={addWrong}>Add (wrong)</button>
<button onClick={addRight}>Add (right)</button>
</>
);
}addWrong passes the same array reference back, so Object.is reports equality and React skips the update. Treat state as read-only and always pass a new object or array.
Cause 2: the parent re-rendered
When a component renders, React renders the elements it returns, and so on down the tree. By default, a re-render of a parent re-renders all of its descendants, whether or not their props changed.
import { useState } from 'react';
function Child() {
console.log('Child rendered');
return <p>I take no props.</p>;
}
function Parent() {
const [count, setCount] = useState(0);
console.log('Parent rendered');
return (
<>
<button onClick={() => setCount(count + 1)}>Parent count: {count}</button>
<Child />
</>
);
}Each click logs both "Parent rendered" and "Child rendered", even though Child has no props and no state. React does not check whether Child needs to run. It runs it, because rendering is cheap compared with the risk of showing stale UI.
A state update re-renders the component that owns the state and everything beneath it. It does not re-render its parent or its siblings.
Children passed as props
There is one important exception to "parents re-render children". Consider this pattern:
import { useState } from 'react';
function Layout({ children }) {
const [open, setOpen] = useState(false);
console.log('Layout rendered');
return (
<div>
<button onClick={() => setOpen(!open)}>Toggle</button>
{open && <p>Extra panel</p>}
{children}
</div>
);
}
function ExpensiveContent() {
console.log('ExpensiveContent rendered');
return <p>Heavy content</p>;
}
export default function App() {
return (
<Layout>
<ExpensiveContent />
</Layout>
);
}When you click Toggle, Layout re-renders, but ExpensiveContent does not. The element <ExpensiveContent /> was created inside App, and App did not render again. React receives the same element object in children as before, and it can reuse the previous result for an identical element. The rule is that React skips a child whose element is the same object as last time and whose own state and context have not changed.
This is a useful technique. Moving state down into a smaller component, or lifting content up and passing it as children, limits the re-render to the part that needs it, without any memoization.
Cause 3: a context value changed
A component that calls useContext(SomeContext) re-renders when the value of the nearest provider changes. React compares the old and new value with Object.is.
import { createContext, useContext, useState } from 'react';
const ThemeContext = createContext('light');
function ThemedLabel() {
const theme = useContext(ThemeContext);
console.log('ThemedLabel rendered with', theme);
return <p>Theme: {theme}</p>;
}
export default function App() {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={theme}>
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Switch
</button>
<ThemedLabel />
</ThemeContext.Provider>
);
}A context re-render ignores the parent chain. A component that reads the context re-renders when the value changes, even if a memoized ancestor between it and the provider skipped rendering.
A common mistake is passing a fresh object as the value:
<ThemeContext.Provider value={{ theme, toggle }}>The object literal is a new object on every render of the provider's component, so every consumer re-renders every time, even when theme and toggle are unchanged. Memoize the value with useMemo, or split it into several contexts.
What does not trigger a re-render
Several things that feel like changes do nothing by themselves:
- Changing a variable declared with
letinside a component. The value is lost on the next render anyway. - Changing a
ref(ref.current = ...). Refs are for values that should not affect the output. - Mutating state objects without calling the setter.
- Changing a module-level variable. React does not watch it.
The table summarizes the triggers.
| Event | Re-renders the component? |
|---|---|
| Its own `setState` with a different value | Yes |
| Its own `setState` with the same value | No visible work |
| Parent renders and returns the element again | Yes |
| Parent renders but passes the same `children` element | No |
| Consumed context value changes | Yes |
| `ref.current` changes | No |
| Local `let` variable changes | No |
Updates use the render's snapshot
A state update does not change the variable in the code that is already running. The count inside a given render is a fixed value for that render. The new value shows up on the next render.
import { useState } from 'react';
function Snapshot() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 5);
console.log(count); // still the old value
}
return <button onClick={handleClick}>Count: {count}</button>;
}The first click logs 0, even though the next render shows 5. This is also why two calls to setCount(count + 1) in a row add only one: both read the same snapshot. Use the updater form setCount(c => c + 1) when the next value depends on the previous one. The batching chapter covers this in detail.
Common mistakes
- Calling a setter during render.
setCount(count + 1)in the body of the component schedules another render, which calls it again, and React stops with a "Too many re-renders" error. Only set state in event handlers, effects, or in the narrow "adjust state while rendering" pattern for the component's own state. - Writing
onClick={setCount(1)}instead ofonClick={() => setCount(1)}. The first form calls the setter immediately during render. - Assuming a re-render means the DOM changed. A re-render is a function call. The DOM changes only if the new output differs.
- Assuming props changing causes the re-render. The parent's render does, and it happens even if the props are equal.
Exercise
A component Page holds const [query, setQuery] = useState('') and renders <SearchBox />, <Results />, and <Footer />, none of which are memoized and none of which read context. Typing in SearchBox calls setQuery, which is defined in Page. Which components render on each keystroke, and how could you stop Footer from re-rendering without using memo?
Show answer
Page re-renders because it owns the state, and SearchBox, Results, and Footer all re-render because their parent rendered. To stop Footer re-rendering, either move the query state into a smaller component that wraps only SearchBox and Results, or have Page's parent create <Footer /> and pass it down as children, so React receives the same element object and skips it.
Exercise
This handler runs when a button is clicked: items.push(newItem); setItems(items);. The list on screen does not update. Why, and what is the fix?
Show answer
The array is mutated in place and the same reference is passed to the setter. React compares the old and new state with Object.is, finds them equal, and skips the update. Pass a new array instead: setItems([...items, newItem]).