Derived State and Avoiding Redundant State
Build, explain and debug React 19 interfaces: components, rendering, state, effects, identity, forms and actions, server components, concurrency, performance and testing, ending with architecture and typing work on real component challenges.
What you will be able to do
#- Compute derived values during render instead of storing them.
- Adjust state during render when a prop changes.
- Recognize when a key reset replaces a syncing effect.
Overview
#Compute during render
If a value can be computed from props or existing state, compute it during render instead of storing it. A derived value computed in render is always consistent with its inputs and adds no extra render.
function Cart({ items }: { items: Item[] }) {
const total = items.reduce((sum, i) => sum + i.price, 0);
return <p>Total: {total}</p>;
}
Why stored derived state drifts
Storing derived data creates a second source of truth. If you forget to update it on every path that changes the source, the copy drifts. Effects that copy props into state also show a stale frame, because the effect runs after the first render.
// avoid: a second copy that can drift and costs a render
const [visible, setVisible] = useState<Item[]>([]);
useEffect(() => setVisible(items.filter((i) => i.done)), [items]);
Adjusting state during render
Sometimes state must change when a prop changes. Instead of an effect, store the previous prop and compare during render. React discards the render and re-runs it immediately with the new state, before committing, so no stale frame is painted.
function List({ items }: { items: Item[] }) {
const [selection, setSelection] = useState(items[0]?.id ?? null);
const [prevItems, setPrevItems] = useState(items);
if (items !== prevItems) {
setPrevItems(items);
setSelection(items[0]?.id ?? null);
}
return <p>{selection}</p>;
}
Pitfall: expensive derivations
Computing during render is cheap for small data, but a heavy sort or filter runs on every render. Wrap only the expensive computation in useMemo, and only after you have measured it. Memoizing a cheap computation adds cost and noise.
Reset instead of sync
When the derived value belongs to a different entity, remount with a key rather than syncing state. A key change resets all state at once with no extra render.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
How many renders happen after items changes, and what is shown on the first one?
Read the code, then choose the best answer. The reference explanation stays hidden until you respond. stimulus.tsxconst [visible, setVisible] = useState<Item[]>([]); useEffect(() => { setVisible(items.filter((i) => i.done)); }, [items]);Exercise 2Implement
Replace the stored derived state with a value computed during render.
starter.tsxfunction Summary({ items }: { items: Item[] }) { const [count, setCount] = useState(0); useEffect(() => setCount(items.length), [items]); return <p>{count} items</p>; }Reveal the reference answer
reference.tsxfunction Summary({ items }: { items: Item[] }) { const count = items.length; return <p>{count} items</p>; }Authored expected output: The count always matches items.length on the first render.
length is derived directly from props, so it needs no state and no effect. Removing both eliminates the extra render and the possibility of drift.
Exercise 3Debug
This component shows the previous user's name for one frame after the id changes. Explain and fix.
starter.tsxfunction Profile({ user }: { user: User }) { const [draft, setDraft] = useState(user); useEffect(() => setDraft(user), [user]); return <h1>{draft.name}</h1>; }Reveal the reference answer
reference.tsxfunction Profile({ user }: { user: User }) { return <h1>{user.name}</h1>; } // or, when local state is genuinely needed, remount at the call site: // <Profile key={user.id} user={user} />Authored expected output: The new user's name is shown on the first render with no stale frame.
The effect copies props into state after commit, so the first render paints the old user. Render the prop directly, or use a key to remount so the first render already uses the new user.
Exercise 4Explain
Explain why storing a value that can be derived from state is discouraged, in terms of consistency and render cost.
starter.tsx// const full = first + ' ' + last; vs const [full, setFull] = useState('')Reveal the reference answer
reference.tsxA derived value stored in state is a second source of truth. Every code path that changes the inputs must also update the copy, and any missed path leaves the copy stale. Storing it also costs an extra render when you sync it through an effect, and that render can paint a stale frame. Computing during render keeps one source of truth and no extra pass.Authored expected output: A written explanation of single source of truth, drift risk and extra render cost.
The argument has two parts: correctness (one source of truth) and cost (no sync render). Both favor computing during render.
Common misconceptions
#- Derived values should be stored so they are computed once. Storing duplicates the source and risks drift; compute in render and memoize only if measured.
- An effect is the right place to sync state to props. Adjusting state during render or remounting with a key avoids the stale frame.
- useMemo makes any computation faster. It adds overhead; use it only for measured heavy work or stable identity.
- Setting state during render is always a bug. The compare-and-set pattern is the documented alternative to syncing effects.
Follow-up practice
#- react-context-performance
- react-custom-hooks
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.