Why does copying props into useState with useEffect cause bugs?
Question
This cart summary receives items ([{ id: "a", price: 30, inStock: true }, { id: "b", price: 50, inStock: false }]) and onlyInStock. On mount, $0 flashes before $80. Toggling onlyInStock to true briefly flashes $80 before $30 and renders twice.
function CartSummary({ items, onlyInStock }: Props) {
const [visible, setVisible] = useState(items);
const [total, setTotal] = useState(0);
useEffect(() => {
const next = onlyInStock ? items.filter((i) => i.inStock) : items;
setVisible(next);
setTotal(next.reduce((sum, i) => sum + i.price, 0));
}, [items, onlyInStock]);
return <p>{visible.length} in cart: ${total}</p>;
}- Trace every render on mount and one toggle, and explain the flashes.
- Rewrite
CartSummarywithout redundant state oruseEffect. - When does
useMemohelp here, and when should you skip it?
Show hints (3)
- "CHECK EFFECT TIMING"
useEffectruns after React renders and commits the DOM. What values dovisibleandtotalhold during the first render after a prop change? - "COMPUTE DURING RENDER"
visibleandtotaldepend only onitemsandonlyInStock. Calculate both directly in the component body with zerouseStateoruseEffect. - "MEASURE BEFORE MEMOIZING"
Small cart filters finish in microseconds. Add
useMemoonly when profiling shows slow work (such as over1 ms) re-running on unrelated state updates.
Show checked explanation
useEffect runs after React commits the DOM, so mirroring props into useState renders stale values first ($0 on mount, $80 after toggling) and triggers a second render pass. Compute visible and total directly during render instead. Add useMemo only if profiling proves the calculation is slow during unrelated re-renders.
Buggy, derived, and useMemo component flows were simulated with a minimal render-and-effect harness on Node.js v24.15.0 and checked in Python 3.12.10 (no React DOM runtime installed); render lifecycle and memoization guidance checked against React 19 documentation. Checked by an editor other than the author.
Walkthrough
Every value in CartSummary comes straight from items and onlyInStock. Storing copies in useState splits one source of truth into three places and forces useEffect to patch them after the browser already saw stale output.
| Step | useState + useEffect (4 renders) | Derived during render (2 renders) |
|---|---|---|
Mount (onlyInStock = false) | Render 1: 2 in cart: $0 (stale) -> Effect -> Render 2: 2 in cart: $80 | Render 1: 2 in cart: $80 |
Toggle (onlyInStock = true) | Render 3: 2 in cart: $80 (stale) -> Effect -> Render 4: 1 in cart: $30 | Render 2: 1 in cart: $30 |
Compute during render. Delete both useState calls and the useEffect. React already re-runs your component whenever items or onlyInStock changes:
function CartSummary({ items, onlyInStock }: Props) {
const visible = onlyInStock
? items.filter((item) => item.inStock)
: items;
const total = visible.reduce((sum, item) => sum + item.price, 0);
return <p>{visible.length} in cart: ${total}</p>;
}Now mount plus one toggle runs 2 renders with 0 stale frames, instead of 4 renders with 2 stale frames. Child components inside CartSummary also avoid wasting work on outdated props.
When useMemo actually helps. Plain render code re-runs whenever the component re-renders, even for unrelated local state like typing into a promo-code input. For 10 cart items, filtering takes microseconds, so useMemo adds dependency comparisons for no real gain. If items has 5,000 rows and profiling shows the filter takes 1 ms or more per keystroke, wrap visible (and total) in useMemo(..., [items, onlyInStock]). Unlike useEffect, useMemo still runs during render, so it never flashes stale data.
Common mistakes
- Copying props into
useStateand syncing them inuseEffect. That doubles render passes and flashes stale UI on every prop update. - Wrapping every tiny calculation in
useMemoby default. Memoization adds memory and dependency-check overhead when filtering a small list takes microseconds. - Relying on
useMemofor side effects or correctness. React treatsuseMemostrictly as a performance cache, not a guarantee that code runs only once. - Passing a fresh inline
itemsarray literal from the parent on every render while usinguseMemo. A new array reference busts the cache every time.
Follow-up questions
- "What if a form actually needs local editable state that resets when a different
userIdprop is selected?" Do not sync it inuseEffect. Passkey={userId}on the child form component so React remounts it cleanly with fresh initial state wheneveruserIdchanges. - "What if you only want to reset one selection field (not the whole subtree) when
itemschanges?" Store the selectedselectedIdinstead of copying the selected object, then deriveconst selected = items.find((i) => i.id === selectedId) ?? nullduring render. That stays in sync automatically whenitemsupdates. - "If React Compiler is enabled in a React 19 app, do you still need manual
useMemo?" Usually far less often, because React Compiler automatically memoizes pure render calculations. You still must remove redundantuseStateplususeEffectmirrors first, because the compiler cannot fix state-sync effects.
What a strong answer covers
Traces all 4 renders and both stale flashes ($0 and $80), removes redundant useState and useEffect by deriving values during render, and explains profiling-driven useMemo versus key resets.
Open in interactive practice deck →