Sub topic 14
Re-rendering cost of controlled inputs
This chapter assumes you can write function components, use useState, and have built a controlled input (an input whose value comes from state and whose onChange writes back to state). It covers why controlled inputs re-render on every keystroke, when that matters, and what to do about it.
Why every keystroke renders
In a controlled input, each keystroke calls setState. React then re-renders the component that owns the state and every child component under it, unless the child is memoized. For a single text field this costs almost nothing. The cost appears when the state lives in a large component, for example a form with 50 fields or a page that also holds a big list.
Measure before you fix
Re-rendering is not the same as slow. A render only calls your function and compares the result with the previous one. The browser updates the DOM only for what changed. Open the React DevTools Profiler, record a few keystrokes, and look at render time per commit. If typing feels smooth, leave the code alone.
Fix 1: move state down
Keep state in the smallest component that needs it. If only the search box needs its text, don't store that text in the page component.
import { useState, memo } from 'react';
const ExpensiveList = memo(function ExpensiveList({ items }) {
return (
<ul>
{items.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
);
});
function SearchBox() {
const [query, setQuery] = useState('');
return (
<input value={query} onChange={(e) => setQuery(e.target.value)} />
);
}
export default function Page({ items }) {
return (
<div>
<SearchBox />
<ExpensiveList items={items} />
</div>
);
}Here query lives in SearchBox, so typing re-renders only that component. Page and ExpensiveList do not run again.
Fix 2: memoize expensive children
memo makes a component skip rendering when its props are shallowly equal to the last render. It only helps if the props stay stable. A new object, array, or inline function created on each render defeats it.
import { useState, useCallback, memo } from 'react';
const Row = memo(function Row({ id, onRemove }) {
return <button onClick={() => onRemove(id)}>Remove {id}</button>;
});
export default function Editor({ ids, onRemove }) {
const [note, setNote] = useState('');
const handleRemove = useCallback((id) => onRemove(id), [onRemove]);
return (
<div>
<textarea value={note} onChange={(e) => setNote(e.target.value)} />
{ids.map((id) => (
<Row key={id} id={id} onRemove={handleRemove} />
))}
</div>
);
}useCallback keeps handleRemove the same function between renders, so each Row can be skipped while the user types in the textarea.
Fix 3: leave the input uncontrolled
If you only need the value at submit time, an uncontrolled input has no per-keystroke state and no re-render. Read it with FormData, as shown in the earlier chapter. Choose this when you don't need live validation or live display of the value.
Fix 4: defer the expensive work
Sometimes the input is cheap but something derived from it is not, such as filtering 10,000 rows. useDeferredValue lets the input update at once while the heavy part lags slightly behind.
import { useState, useDeferredValue, useMemo } from 'react';
export default function FilteredList({ items }) {
const [query, setQuery] = useState('');
const deferredQuery = useDeferredValue(query);
const visible = useMemo(
() => items.filter((item) => item.includes(deferredQuery)),
[items, deferredQuery]
);
return (
<div>
<input value={query} onChange={(e) => setQuery(e.target.value)} />
<ul>
{visible.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
</div>
);
}Common errors
- Adding
memoanduseCallbackeverywhere without profiling. This adds code and comparison work for no gain. - Passing inline objects such as
style={{ color: 'red' }}to a memoized child, which breaks memoization. - Defining a component inside another component. React treats it as a new component each render and remounts it, so inputs lose focus on every keystroke.
Choosing a fix
| Situation | Best first step |
|---|---|
| State sits too high in the tree | Move state into the component that uses it |
| Heavy sibling re-renders while typing | Wrap the sibling in `memo` |
| Expensive filtering from the input | `useDeferredValue` |
| Value needed only on submit | Uncontrolled input with `FormData` |
| Many fields with complex rules | Consider a form library |
Exercise
A page component holds a query state for a search input and also renders a slow, unmemoized chart. Typing in the input feels laggy. Name two changes that would fix this and say why each works.
Show answer
First, move query into a small SearchBox component, so typing re-renders only that component and not the page or chart. Second, wrap the chart in memo with stable props, so React skips it when the parent re-renders. Moving state down is usually the simpler choice.
Exercise
You wrapped a child in memo, but it still re-renders on every keystroke in the parent. The parent passes onSelect={(id) => select(id)} to it. What is the cause and the fix?
Show answer
The inline arrow function is a new function on every render, so the shallow prop comparison sees a changed prop. Wrap the handler in useCallback with the right dependencies, or pass a stable function reference.