Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 7.6 — You Might Not Need an Effect
React · Example 1 of 3

Derived data: an effect costs an extra render

BadName first renders with an empty name (a flash of wrong UI) and needs a second render. GoodName is right the first time. useMemo skips the filtering on the unrelated re-render because todos and filter didn't change.

If no outside system is involved, you usually don't need an effect: calculate derived data during render (with useMemo if it's slow), reset state with a key, put user-caused logic in event handlers, and run app-wide setup once at module level.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Remove the effect: ``jsx function Cart({ items }) { const [total, setTotal] = useState(0); useEffect(() => { setTotal(items.reduce((s, i) => s + i.price, 0)); }, [items]); return <p>Total: {total}</p>; }

02

A <ChatThread threadId={id} /> keeps a draft and a scrollTop in state, and both must reset when the thread changes. Show the fix in the parent.

Explain it without notes

01

Why is storing derived data in state and updating it with an effect a mistake?

02

How do you reset all of a component's state when a prop changes, without an effect?

03

A child calls onChange from an effect when its state changes. What's wrong, and what's the fix?

04

Where should code go that must run exactly once when the app loads?

Derived data: an effect costs an extra render

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

BadName render: ""
GoodName render: "Asha Rao"
filtering 3 todos
BadName render: "Asha Rao"
--- unrelated re-render
BadName render: "Asha Rao"
GoodName render: "Asha Rao"