Sub topic 14
Re-rendering cost of controlled inputs
This chapter assumes you know useState, controlled inputs (value plus onChange), and basic props. It explains why a controlled input re-renders its component on every keystroke, when that matters, and which fixes to try first.
Why every keystroke renders
A controlled input has no value of its own. Each keystroke follows the same path:
- The browser fires an input event.
- React calls your
onChangehandler. - The handler calls
setStatewith the new text. - React calls the component function again with the new state.
- React compares the new output with the old output and updates the DOM only where it differs.
A render is a call to your component function. It is not a DOM update. For a small form, the render is a few microseconds of JavaScript and the DOM changes by one attribute. This cost is normal and almost never needs fixing.
The cost appears in step 5 of the list above, or rather in the child renders in the diagram. By default, when a component renders, every component it returns also renders, even when its props did not change. If the form shares a component with something expensive, each keystroke pays for that expensive part too.
Seeing the problem
The following page has one input and a list of 5,000 items. The list does not depend on the input, but it sits beside it in the same component.
import { useState } from 'react';
const items = Array.from({ length: 5000 }, (_, i) => `Item ${i}`);
function SlowList({ items }) {
console.log('SlowList render');
return (
<ul>
{items.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
);
}
export default function Page() {
const [title, setTitle] = useState('');
return (
<>
<input value={title} onChange={(e) => setTitle(e.target.value)} />
<SlowList items={items} />
</>
);
}Type three letters and the console prints SlowList render three times. The items array is the same object each time, and the list still renders again. Nothing in the DOM changes, because the diff finds identical output, but the 5,000 elements are still created and compared on every keystroke. On a slow device the input starts to lag.
Measure before changing anything
Do not guess. Use the React DevTools Profiler: record, type a few characters, and look at which components rendered and how long each took. A render that takes under a few milliseconds is not worth optimizing. Lag you can feel while typing usually shows up as a single component taking tens of milliseconds.
Also profile a production build. Development mode runs extra checks, including Strict Mode double renders, so it exaggerates the cost.
Fix 1: move state down
State should live as close as possible to the components that use it. If only the input needs title, put title in a component that contains only the input.
import { useState } from 'react';
const items = Array.from({ length: 5000 }, (_, i) => `Item ${i}`);
function SlowList({ items }) {
console.log('SlowList render');
return (
<ul>
{items.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
);
}
function TitleField() {
const [title, setTitle] = useState('');
return <input value={title} onChange={(e) => setTitle(e.target.value)} />;
}
export default function Page() {
return (
<>
<TitleField />
<SlowList items={items} />
</>
);
}Now typing renders only TitleField. Page does not render again, so SlowList is never asked to. This is the best fix because it adds no memoization and no hooks. It works whenever the expensive part does not need the typed value.
The limit is that sometimes the sibling does need the value. A live preview or a filtered list reads what the user typed, so the state cannot move down.
Fix 2: skip renders with memo
React.memo wraps a component so React skips rendering it when its props are shallowly equal to the previous props.
import { memo, useState } from 'react';
const items = Array.from({ length: 5000 }, (_, i) => `Item ${i}`);
const SlowList = memo(function SlowList({ items }) {
console.log('SlowList render');
return (
<ul>
{items.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
);
});
export default function Page() {
const [title, setTitle] = useState('');
return (
<>
<input value={title} onChange={(e) => setTitle(e.target.value)} />
<SlowList items={items} />
</>
);
}SlowList now renders once. The state stays in Page, so this also works when a sibling reads title, as long as the memoized component does not receive it.
How memo breaks
Shallow comparison uses Object.is on each prop. Props created during render are new objects every time, so the memo never hits:
// Defeats memo: a new array and a new function on every render
<SlowList items={allItems.filter(Boolean)} onSelect={(id) => select(id)} />To keep memo effective, pass stable references. Define constants outside the component, or wrap derived values in useMemo and callbacks in useCallback. If you memoize a component and then pass it an inline object, you have added comparison work and saved nothing. Check the Profiler to confirm the skip actually happens.
If your project uses the React Compiler, it inserts much of this memoization automatically, but moving state down is still worth doing first.
Fix 3: defer the expensive work
Sometimes the typed value must reach an expensive component, such as a search that filters thousands of rows. Here the input itself must stay responsive while the results may lag slightly. useDeferredValue returns a copy of a value that React updates at lower priority.
import { memo, useDeferredValue, useState } from 'react';
const ALL = Array.from({ length: 20000 }, (_, i) => `Product ${i}`);
const Results = memo(function Results({ query }) {
const matches = ALL.filter((name) =>
name.toLowerCase().includes(query.toLowerCase())
);
return (
<ul>
{matches.slice(0, 200).map((name) => (
<li key={name}>{name}</li>
))}
</ul>
);
});
export default function Search() {
const [query, setQuery] = useState('');
const deferredQuery = useDeferredValue(query);
return (
<>
<input value={query} onChange={(e) => setQuery(e.target.value)} />
<Results query={deferredQuery} />
</>
);
}The input is bound to query, so it updates immediately. Results receives deferredQuery, which keeps its old value while React handles the urgent input update, then catches up. React can also interrupt the slow render if you type again. The memo wrapper matters here: during the urgent render, deferredQuery has not changed, so Results is skipped.
Do not debounce the controlled value
A common mistake is to delay setState itself, for example with a timer, to reduce renders. This breaks the input. React sets the DOM value from state after each event. If state has not caught up, React puts the old text back and the user's character disappears or the cursor jumps.
Keep the controlled value updating synchronously in the handler. If you need fewer expensive operations, such as network requests, debounce the work that reads the value, not the value itself.
Choosing a fix
| Situation | First choice | Why |
|---|---|---|
| Input state is not used by an expensive sibling | Move state down | No extra APIs, no comparison cost |
| Expensive sibling does not receive the typed value | `memo` with stable props | Keeps state where it is |
| Expensive child needs the typed value | `useDeferredValue` plus `memo` | Input stays responsive |
| Many fields, none read until submit | Uncontrolled inputs with `FormData` | No render per keystroke at all |
| Large form with many validated fields | Form library | Subscribes per field |
Uncontrolled inputs avoid the cost completely, because the DOM holds the value and React does not render while the user types. You give up live validation and live previews, so choose them only when you do not need the value before submit.
Common mistakes
- Optimizing without measuring. Most forms render fast enough as written.
- Putting every field in one state object at the top of a large page, then memoizing everything to compensate. Split the form into field components first.
- Memoizing a component but passing it inline objects or functions.
- Delaying the controlled value with a timer, which drops characters.
Exercise
A page holds const [search, setSearch] = useState('') next to a <Chart data={bigData} /> component that takes 80 ms to render. Typing in the search input lags, but Chart does not use search. Name two fixes that do not change what the user sees, and say which you would try first.
Show answer
Move the search state and input into their own component so Page no longer renders on each keystroke, or wrap Chart in memo and pass it a stable bigData reference. Try moving state down first. It needs no memoization and cannot be defeated by an unstable prop. Confirm the result in the React Profiler.
Exercise
A developer tries to reduce renders by calling setTimeout(() => setName(value), 300) inside onChange of a controlled input. What goes wrong, and what should they do instead?
Show answer
React resets the input's DOM value to the current state after each event, so until the timer fires the input shows the old text. Typed characters vanish or the cursor jumps. They should update state immediately in onChange and debounce only the expensive work that reads the value, or use useDeferredValue for the expensive child.