Sub topic 8
Fixing renders by moving state down
This chapter assumes you can write React function components with props, state, and hooks. It also assumes you have recorded a session in the React DevTools Profiler and can tell which components rendered. The previous chapters covered how to find unnecessary re-renders. Here you fix them by changing where state lives, which is often cheaper and safer than adding memoization.
The core idea: state colocation
State colocation means keeping state as close as possible to the components that use it. When a component's state changes, React re-renders that component and every child component it returns, even if the children's props did not change. The larger the subtree under the state owner, the more work each update causes.
If a piece of state is used by only a small part of the tree, moving it into that part shrinks the set of components that re-render. No comparison logic is needed, and nothing can go stale.
A worked example
Consider a page where typing in a search input re-renders an expensive tree.
import { useState } from "react";
function SlowPage() {
const [query, setQuery] = useState("");
return (
<>
<input value={query} onChange={(e) => setQuery(e.target.value)} />
<ExpensiveTree />
</>
);
}Every keystroke calls setQuery. SlowPage re-renders, and so does ExpensiveTree, because it is a child that SlowPage returns. ExpensiveTree does not read query, so the work is wasted.
In the Profiler, this shows up as ExpensiveTree highlighted in the flamegraph on every commit. When you select it, the "Why did this render?" panel says the parent component rendered.
The fix is to move the state into a small component of its own.
import { useState } from "react";
function SearchBox() {
const [query, setQuery] = useState("");
return <input value={query} onChange={(e) => setQuery(e.target.value)} />;
}
function FastPage() {
return (
<>
<SearchBox />
<ExpensiveTree />
</>
);
}Now setQuery belongs to SearchBox. Only SearchBox and its children re-render. FastPage does not re-render, so ExpensiveTree is not touched.
Record a new session with the same typing and compare. The flamegraph should show only SearchBox rendering, and the commit durations should drop to a fraction of a millisecond.
Why this works
React decides what to render by starting at the component whose state changed and walking down. It does not look at ancestors or siblings. By lowering the state owner in the tree, you lower the starting point of that walk.
Because the diagram syntax must use the specified fence, here is the same idea as a proper diagram.
When state is needed in two places
Colocation is easy when one component uses the state. Often two siblings need it. For example, a search box and a results list both need query.
You then lift the state to the nearest common parent, and that parent re-renders on every change. Moving state down no longer works for the whole state, but you can still limit the damage with the pattern below.
Pass expensive content as children
A component that holds state can render children it received from above. The children element was created by the parent, not by the stateful component. When the stateful component re-renders, React sees that the children prop is the same element object and skips it.
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 default function App() {
return (
<ColorPicker>
<ExpensiveTree />
</ColorPicker>
);
}ColorPicker re-renders on every keystroke. ExpensiveTree does not, because App created the <ExpensiveTree /> element once and App did not re-render. React reuses the same element and bails out.
This works with any prop that holds an element, not only children. A named prop such as sidebar={<Sidebar />} behaves the same way.
Split a component along its state boundary
When a component mixes fast-changing state with slow content, extract the part that uses the state. Look in the Profiler for the component that renders often and contains both kinds of content. Then ask which JSX depends on the state, and move that JSX and the state into a new component.
Common mistakes
- Moving state too far down. If a sibling later needs the value, you have to lift it again. Move state down only as far as the current consumers require.
- Creating the children inside the stateful component. Writing
<ExpensiveTree />insideColorPickermakes a new element on each render. The bail-out only works when the element comes from a parent that did not re-render. - Expecting a fix when the parent re-renders anyway. If
Appitself re-renders because of its own state,<ExpensiveTree />is a new element again, and the children pattern no longer helps. - Moving state that belongs to a shared concern. Form values that must be submitted together, or state that other features read, should stay where all readers can reach it.
- Skipping the measurement. A subtree that renders in 0.2 ms does not need restructuring. Check
actualDurationfirst.
Choosing between colocation and memoization
| Situation | Preferred fix | Reason |
|---|---|---|
| One small part of the tree uses the state | Move state down | No dependency lists or equality checks to maintain |
| A stateful parent wraps expensive, independent content | Pass the content as `children` | The element identity stays the same |
| Several distant components read the same state | Lift state, then use `React.memo` on children | Colocation cannot separate them |
| A calculation is costly on its own | `useMemo` | The cost is inside one component, not in the tree shape |
Try colocation first. It removes the cause of the extra render, while memoization hides the symptom and adds code you must keep correct. The next chapter covers memoization in detail.
Verifying the change
- Record a Profiler session before the change, performing the same interaction, such as typing ten characters.
- Note the number of commits, the components that rendered in each, and the total
actualDuration. - Apply the restructuring.
- Record again with the same interaction and compare.
Use a production build for final numbers, as discussed in the chapter on development and production builds. Development builds add checks that make absolute times larger, though the set of components that rendered remains a reliable signal.
Exercise
A component Dashboard holds const [hover, setHover] = useState(false) and renders a <Tooltip hover={hover} /> next to a large <Chart data={data} />. Every mouse move over the tooltip re-renders Chart. Describe two ways to stop this without using React.memo.
Show answer
First, move the hover state into a new component, such as TooltipArea, that renders the tooltip and handles the mouse events. Dashboard then no longer owns the state, so it does not re-render and Chart is untouched. Second, if Dashboard must keep the state, turn it into a wrapper that receives the chart as children from a parent that does not re-render, for example <HoverShell><Chart data={data} /></HoverShell>. The Chart element is created by the parent, so React reuses it when HoverShell re-renders.
Exercise
You apply the children pattern, but the Profiler still shows ExpensiveTree rendering on each keystroke. What is the most likely cause, and how do you confirm it?
Show answer
The component that creates the <ExpensiveTree /> element is itself re-rendering, so a new element is made each time. Confirm it by selecting ExpensiveTree in the Profiler with "Record why each component rendered" enabled. If the reason is that the parent rendered, find which ancestor re-rendered and why, then move the state out of that ancestor or restructure it.