An effect chain versus calculating during render
One click on the broken cart renders three times, and two of those renders show a wrong state (60 in the cart, but total 40; then total 60 but no free shipping). The fixed cart renders once with consistent values, and has two fewer state variables to keep in sync.
Six mistakes show up in almost every React codebase: copying props into state, chains of effects that set state, index keys on lists that change, giant components, drilling every prop everywhere, and memoising by reflex; each has a small, well-known fix taught earlier in this course.
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.
Refactor: function Price({ amount, rate }) { const [converted, setConverted] = useState(0); useEffect(() => { setConverted(amount * rate); }, [amount, rate]); return <span>{converted.toFixed(2)}</span>; }
This list uses key={i} and each row has a checkbox with local state. Items can be sorted. What breaks, and how do you fix it?
Explain it without notes
Why is copying a prop into state a bug, and what are the fixes?
What is wrong with a chain of effects that set state, and how do you refactor it?
Why do index keys cause bugs, and when are they acceptable?
How would you approach memoisation in a React codebase?
Preview
Console
Nothing logged yet.Expected console output
broken render: total 40 free false
fixed render: total 40 free false
--- click both
broken render: total 40 free false
broken render: total 60 free false
broken render: total 60 free true
fixed render: total 60 free true