Skip to content

QuizNot attempted

Inline callback as an effect dependency

Clicking the button 3 times — how many times does 'updated' log (including mount)?
function Child({ onUpdate }) {
useEffect(() => {
onUpdate();
}, [onUpdate]);
return null;
}
function Parent() {
const [count, setCount] = useState(0);
const handleUpdate = () => console.log('updated');
return (
<div>
<Child onUpdate={handleUpdate} />
<button onClick={() => setCount(c => c + 1)}>{count}</button>
</div>
);
}
1–4 to choose, Enter to submit
Show answer & explanation

Correct answer:

  • 4
  • handleUpdate is a new function on every Parent render, so onUpdate fails the Object.is comparison each time and the child's effect re-runs: mount + 3 clicks = 4.
  • Not 1: that needs a stable reference (useCallback).
  • Not 3: the mount run also logs.
  • Not 0: effects always run after mount.