Chapter 2 · Practice 1 of 5
Keep state minimal and derive everything else during render
From State and data flow
Why it matters
Every extra piece of state is something you have to keep in sync, and sooner or later stored copies drift apart. If a value can be calculated from props or other state, do not store it.
| Stored (avoid) | Derived (prefer) |
|---|---|
fullName next to firstName and lastName | Join the two names in render |
filteredItems next to items and query | Filter items by query in render |
Calculate derived values directly in the component body. It is cheap for almost all data, and React Compiler will memoize it for you when it matters.
Do
- Store the source of truth once, compute views of it in render
Avoid
- An effect that sets one piece of state from another
Example
function Products({ items }: { items: Product[] }) {
const [query, setQuery] = useState('');
// Derived, not stored
const visible = items.filter((p) =>
p.name.toLowerCase().includes(query.toLowerCase())
);
return <Results items={visible} onSearch={setQuery} />;
}