Sub topic 9
Cheaper fixes: move state down and pass children
Memoization is one way to stop wasted renders. Often a simpler change to the component structure removes the problem without any caching code. This chapter covers two such changes: moving state down and passing children. It also covers how to pick between them and memo.
This chapter assumes you know function components, JSX, useState, and how props and children flow between components. It also assumes you know that React re-renders a component when its state changes, and that by default it re-renders that component's descendants too.
Why structure comes before caching
A re-render is cheap when the component is small. It is expensive when a state change near the top of the tree forces a large subtree to run again, although nothing in that subtree depends on the new value.
There are two ways to fix that:
- Make the subtree skip the render with
memo,useMemo, anduseCallback. This adds comparison work and dependency arrays that you must keep correct. - Change where the state lives, so the subtree is never inside the component that re-renders.
The second option has no runtime cost and no dependency arrays to get wrong. That is why it is usually worth trying first, after you have measured and confirmed which component is slow.
Technique 1: move state down
State colocation means keeping state in the component closest to the code that uses it. When state sits higher than it needs to, every change re-renders everything below.
Here is a page where the search text lives in the parent, next to a slow subtree:
import { useState } from 'react';
export function Page() {
const [query, setQuery] = useState('');
return (
<>
<input value={query} onChange={(e) => setQuery(e.target.value)} />
<ExpensiveTree />
</>
);
}
function ExpensiveTree() {
// Imagine a large subtree here.
return <div>Large content</div>;
}Every keystroke calls setQuery. That re-renders Page, and Page re-renders ExpensiveTree even though ExpensiveTree takes no props and ignores query.
The fix is to move the state into a component of its own:
import { useState } from 'react';
export function Page() {
return (
<>
<SearchBox />
<ExpensiveTree />
</>
);
}
function SearchBox() {
const [query, setQuery] = useState('');
return <input value={query} onChange={(e) => setQuery(e.target.value)} />;
}
function ExpensiveTree() {
// Imagine a large subtree here.
return <div>Large content</div>;
}Now query belongs to SearchBox. A keystroke re-renders only SearchBox and its children. Page does not re-render, so ExpensiveTree is not asked to render. No memo is involved.
When moving state down works
The technique works when only part of the parent's output uses the state. To find the right place, ask which JSX actually reads the value or calls the setter. Then extract that JSX and the state into a new component.
If the state is also read by a sibling, move it down only as far as the closest common parent of everything that uses it.
A related case: derived UI that depends on the state
Sometimes the slow subtree needs the state, but only a small part of the page does. Extract the part that reads the state and leave the rest alone.
import { useState } from 'react';
export function Dashboard({ report }) {
return (
<section>
<ThemeToggle>
<HeavyReport report={report} />
</ThemeToggle>
</section>
);
}
function ThemeToggle({ children }) {
const [dark, setDark] = useState(false);
return (
<div className={dark ? 'dark' : 'light'}>
<button onClick={() => setDark((d) => !d)}>Toggle theme</button>
{children}
</div>
);
}
function HeavyReport({ report }) {
return <pre>{JSON.stringify(report, null, 2)}</pre>;
}This example already uses the second technique, passing children, which is covered next.
Technique 2: pass children
Sometimes state cannot move down because the component that owns it also needs to wrap the slow content. A color theme, a scroll position, or an open/closed panel often fits this pattern. The wrapper needs the state, but the content inside it does not.
The solution is to accept the content as children. Props such as children are created by the component that renders the wrapper, not by the wrapper itself.
Compare these two versions. In the first, the slow part is created inside the stateful component:
import { useState } from 'react';
export function App() {
const [color, setColor] = useState('red');
return (
<div style={{ color }}>
<input value={color} onChange={(e) => setColor(e.target.value)} />
<ExpensiveTree />
</div>
);
}
function ExpensiveTree() {
return <div>Large content</div>;
}Each change to color re-renders App. The <ExpensiveTree /> element is created again on every render of App, so React renders it again.
In the second version, the stateful part is split out and takes the slow part as children:
import { useState } from 'react';
export function App() {
return (
<ColorPicker>
<ExpensiveTree />
</ColorPicker>
);
}
function ColorPicker({ children }) {
const [color, setColor] = useState('red');
return (
<div style={{ color }}>
<input value={color} onChange={(e) => setColor(e.target.value)} />
{children}
</div>
);
}
function ExpensiveTree() {
return <div>Large content</div>;
}App now creates the <ExpensiveTree /> element. App has no state, so it does not re-render when the color changes. When ColorPicker re-renders, it receives the same children value as before, which is the same element object. React sees that this element has not changed and reuses the previous result instead of rendering ExpensiveTree again.
Why this works
A JSX tag such as <ExpensiveTree /> is shorthand for a call that creates a plain object (a React element) describing what to render. When a component re-renders, React compares the new element it gets for each child position with the one from the last render. If the element is the very same object (referential equality, from the earlier chapter), React skips that child.
In the first version, App re-runs and builds a new element object every time. In the second, App does not run, so the element object stays the same, and ColorPicker merely passes it along.
Passing components in other props
children is the common case, but any prop can carry an element. A layout component can take sidebar and content props that are already-built elements:
import { useState } from 'react';
export function Layout({ sidebar, content }) {
const [collapsed, setCollapsed] = useState(false);
return (
<div>
<button onClick={() => setCollapsed((c) => !c)}>Toggle sidebar</button>
{!collapsed && <aside>{sidebar}</aside>}
<main>{content}</main>
</div>
);
}
export function App() {
return <Layout sidebar={<nav>Links</nav>} content={<article>Body</article>} />;
}Toggling the sidebar re-renders Layout, but content is an element created by App. It keeps the same identity, so React skips it.
Limits and failure modes
Both techniques depend on who creates the element and who owns the state. They fail in these cases:
- The parent re-renders for another reason. If
Appitself re-renders because of its own state or because its parent re-renders, it creates new elements and the benefit is gone. These techniques only isolate the state change you moved. - Props change. If
ExpensiveTreereceives a prop that changes, it must render. Moving state does not avoid real work. - The state is genuinely shared. If many distant components read the same value, you cannot move it down. At that point you use context (next chapters) or a state library, and you may need
memofor the consumers. - The wrapper reads children. If
ColorPickerinspectschildren, for example withReact.Children.mapandcloneElement, it may produce new elements and lose the identity. Passingchildrenthrough untouched keeps it. - Passing functions, not elements. A render prop such as
renderContent={() => <ExpensiveTree />}creates a new element each time the wrapper calls it. That gives no savings.
Choosing between the options
Use this table when a measured slowdown points at an unneeded subtree render.
| Situation | First choice | Why |
|---|---|---|
| Only part of a component's JSX uses the state | Move state down | No caching code, no dependency arrays |
| A stateful wrapper surrounds slow content that does not use the state | Pass children | The wrapper re-renders, the content is reused |
| The same component re-renders with unchanged props from a parent you cannot restructure | `memo` | Skips the render by comparing props |
| A single calculation is slow | `useMemo` | Caches the result, not the render |
| State is shared by distant components | Context plus `memo` | Restructuring cannot isolate it |
A practical order is to measure with the Profiler, restructure if the code allows it, and add memo, useMemo, or useCallback only for what remains.
Common mistakes
- Moving state too far. If two siblings need the value, moving it into one of them breaks the other. Stop at their shared parent.
- Extracting a component and leaving state behind. The new component must own the state. Passing the state in as props from the parent leaves the parent re-rendering.
- Assuming the Profiler shows nothing changed. In the Profiler, a skipped component appears grayed out for that commit. If
ExpensiveTreestill shows a render time after your change, find which ancestor re-rendered. - Over-splitting. Creating many tiny wrappers for components that are cheap anyway adds files and indirection with no measurable gain.
Verifying the change
Check the result instead of trusting it. Add a log to the slow component and type in the input:
function ExpensiveTree() {
console.log('render ExpensiveTree');
return <div>Large content</div>;
}In the "before" version, the message prints on every keystroke. In the "after" version, it prints once on mount. In development with Strict Mode, React deliberately renders components twice on mount, so expect two logs at startup and none while typing. For timing rather than counts, record a session in the React DevTools Profiler and compare the commit durations.
Exercise
A component Settings holds const [open, setOpen] = useState(false) and renders a toggle button, a panel shown when open is true, and a <HugeTable rows={rows} /> that does not use open. Clicking the button makes the page feel slow because HugeTable re-renders. Describe two changes that fix this without using memo.
Show answer
First, move the state down: extract the button and panel into a new component such as SettingsPanel that owns open, and render <SettingsPanel /> and <HugeTable rows={rows} /> as siblings in Settings. Clicking then re-renders only SettingsPanel. Second, pass children: make a wrapper component that owns open and renders {children}, and have Settings (which has no state) pass <HugeTable rows={rows} /> as the children. The element is created by Settings, which does not re-render, so React reuses it. Both fail if Settings itself re-renders for another reason, because it would create a new HugeTable element.
Exercise
In the children version of ColorPicker, you change ColorPicker to render {React.Children.map(children, (child) => cloneElement(child, { color }))}. Why does ExpensiveTree now re-render on every color change?
Show answer
cloneElement creates a new element object on each render of ColorPicker, and it also passes a new color prop. React sees a different element with changed props, so it must render ExpensiveTree again. The identity of the original children element is no longer what gets rendered.