Sub topic 13
Compute Derived Values During Render
This chapter assumes you can write function components, call useState, and read the snapshot model from earlier chapters. It also assumes you know map, filter, and spread syntax. Here you will learn to spot values that should not be state, and to compute them while the component renders.
What "derived" means
A derived value can be calculated from other data you already have, such as props, state, or both. A filtered list is derived from the full list and the search text. A total price is derived from the cart items. A "form is valid" flag is derived from the field values.
State is for data that the component must remember and that cannot be calculated from anything else. If you can compute a value, storing it adds a second copy that must be kept in sync.
The problem with storing a derived value
This version keeps the visible items in their own state variable:
import { useState } from 'react';
function BrokenFilter({ items }) {
const [query, setQuery] = useState('');
const [visible, setVisible] = useState(items);
function handleChange(e) {
const next = e.target.value;
setQuery(next);
setVisible(items.filter(item => item.toLowerCase().includes(next.toLowerCase())));
}
return (
<>
<input value={query} onChange={handleChange} />
<p>{visible.length} of {items.length} match</p>
</>
);
}It works until the parent passes a new items array. useState(items) uses its argument only on the first render, so visible keeps showing the old list. The counter then reads something like "3 of 10 match" while the real list holds 10 items and the first three never matched anything new. Every place that changes query or items must now remember to update visible too, and one forgotten call produces a stale screen.
Compute it during render
Remove the extra state and calculate the value in the component body:
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>
</>
);
}There is one source of truth for the search text (query) and one for the data (items). visible cannot disagree with either, because it is rebuilt from both on every render.
Why this works
A state update schedules a new render. React calls your component function again, and each call gets a fresh snapshot of props and state. Any const in the body is created again from that snapshot. A derived value therefore always matches the render it appears in, with no extra bookkeeping.
How to decide what is state
Ask these questions about each value, in order.
| Question | If yes |
|---|---|
| Does it come from a parent as a prop? | It is not state in this component. |
| Does it stay unchanged over time? | It is not state. Use a constant. |
| Can you calculate it from props or other state? | It is derived. Compute it during render. |
| Otherwise | It is state. |
Derive from props too
Props are inputs just like state. A value built from props should also be computed, not copied:
function Greeting({ firstName, lastName }) {
const fullName = `${firstName} ${lastName}`;
return <h2>Hello, {fullName}</h2>;
}Writing useState(firstName + ' ' + lastName) would freeze the name at the first render. Later prop changes would be ignored.
Store an id, not a copy of an object
Selection is a common source of duplicated data. Storing the whole selected object makes a copy that goes stale when the list changes. Store the id and look the object up:
import { useState } from 'react';
function ContactList({ contacts }) {
const [selectedId, setSelectedId] = useState(null);
const selected = contacts.find(c => c.id === selectedId) ?? null;
return (
<>
<ul>
{contacts.map(c => (
<li key={c.id}>
<button onClick={() => setSelectedId(c.id)}>{c.name}</button>
</li>
))}
</ul>
<p>{selected ? `Selected: ${selected.name}` : 'Nobody selected'}</p>
</>
);
}If a contact is renamed in the parent, selected.name updates automatically. If the selected contact is removed, find returns undefined, and the ?? null turns that into null, so the component shows the empty state instead of a stale record.
Derive without mutating
Derived values are calculated from props and state, which you must not change. Some array methods change the array they are called on. sort and reverse do this, and toSorted and toReversed do not. Calling items.sort() in the body would reorder the parent's array.
function SortedList({ items }) {
const sorted = [...items].sort((a, b) => a.localeCompare(b));
return (
<ul>
{sorted.map(item => (
<li key={item}>{item}</li>
))}
</ul>
);
}Copy first with spread, then sort the copy.
When the calculation is expensive
Most derived values are cheap. Filtering a few hundred items takes microseconds, so do not optimize by default. If you measure a real slowdown, for example in the React DevTools profiler, wrap the calculation in useMemo:
import { useMemo, useState } from 'react';
function BigFilter({ items }) {
const [query, setQuery] = useState('');
const visible = useMemo(
() => items.filter(item => item.toLowerCase().includes(query.toLowerCase())),
[items, query]
);
return (
<>
<input value={query} onChange={e => setQuery(e.target.value)} />
<p>{visible.length} of {items.length} match</p>
</>
);
}useMemo caches the result and recalculates only when items or query changes. It is a performance tool, not a correctness tool. The code behaves the same without it, only slower. A wrong dependency list gives you the same stale-data bug you were avoiding.
Common errors
- Syncing with an effect. Code like
useEffect(() => setVisible(filtered), [items, query])forces an extra render with an outdated value on screen first. Compute the value directly instead. - Two variables for one fact.
countandisEmptyas separate state can contradict each other. Keepcountand deriveconst isEmpty = count === 0. - Mutating props while deriving. Calling
sort,reverse, orspliceon a prop changes the parent's data. Copy first. - Storing objects that also live in a list. Store the id, as in the contacts example.
- Deriving in the handler only. Calculating a value inside an event handler and saving it with
setStateis the same duplication as the first example.
Exercises
Exercise
A component has const [items, setItems] = useState([]) and const [total, setTotal] = useState(0). Every handler that changes items also calls setTotal. What is wrong with this design, and how do you fix it? Assume each item has a numeric price.
Show answer
total can be calculated from items, so storing it creates a second copy that can go out of sync if any handler forgets to call setTotal. Remove the total state and write const total = items.reduce((sum, item) => sum + item.price, 0); in the component body.
Exercise
A list component calls const sorted = items.sort(compare); in its body, where items is a prop. Why is this a bug, and what is the fix?
Show answer
sort reorders the array it is called on, so it mutates the parent's items array during render. Copy first: const sorted = [...items].sort(compare);. You can also use items.toSorted(compare) in environments that support it.