Sub topic 13
Compute derived values during render
This chapter assumes you know how useState works, how to update state from event handlers, and how to pass props. You should also be comfortable with map and filter.
The problem: state that copies other state
Derived data is any value you can calculate from props or existing state. A common mistake is to store it in its own state variable. That creates two sources of truth, and you must remember to update both every time.
Here is the pattern to avoid:
import { useState } from 'react';
function FilterBad({ items }) {
const [query, setQuery] = useState('');
const [visible, setVisible] = useState(items);
function handleChange(e) {
setQuery(e.target.value);
setVisible(
items.filter(item =>
item.toLowerCase().includes(e.target.value.toLowerCase())
)
);
}
return (
<>
<input value={query} onChange={handleChange} />
<p>{visible.length} of {items.length} match</p>
</>
);
}This breaks when the parent passes a new items array. visible still holds the old list, because useState(items) only uses its argument on the first render. The count is now stale.
The fix: calculate during render
React runs your component function on every render. Any value computed in the function body is therefore always based on the latest props and state.
import { useState } from 'react';
function Filter({ items }) {
const [query, setQuery] = useState('');
const visible = items.filter(item =>
item.toLowerCase().includes(query.toLowerCase())
);
return (
<>
<input value={query} onChange={e => setQuery(e.target.value)} />
<p>{visible.length} of {items.length} match</p>
</>
);
}Only query is state. visible is an ordinary const. It cannot go out of sync, and the handler has one job.
A rule of thumb
For each value, ask whether it can be computed from something you already have. If it can, don't store it.
| Value | Store in state? | Reason |
|---|---|---|
| The text in a search box | Yes | It comes from the user and nothing else determines it. |
| The filtered list | No | It follows from `items` and `query`. |
| `fullName` from `firstName` and `lastName` | No | Join the two strings during render. |
| The number of completed todos | No | Call `todos.filter(t => t.done).length`. |
Cost and common errors
Recomputing on every render is usually cheap. Measure before you optimize. If a calculation is slow, useMemo can cache it, but that is an optimization and not a replacement for deriving.
Watch for these errors:
- Copying a prop into state with
useState(props.value). The state ignores later prop changes. - Calling a setter during render to sync one value to another. This causes extra renders. Derive the value instead.
- Mutating props or state while computing. Use
filter,map, or a copy such as[...items].sort(...), becausesortchanges the original array.
Exercise
A component has const [todos, setTodos] = useState([]) and const [doneCount, setDoneCount] = useState(0). Why is doneCount a poor choice, and what should replace it?
Show answer
doneCount can be calculated from todos, so storing it creates a second source of truth that can fall out of sync. Remove the state and compute const doneCount = todos.filter(t => t.done).length; in the component body.