useEffect Cleanup Order
Predict Output Medium
Question
What does this code print?
Code
function App() {
const [show, setShow] = useState(true);
return show ? <Child onRemove={() => setShow(false)} /> : null;
}
function Child({onRemove}) {
useEffect(() => {
console.log("mount");
return () => console.log("cleanup");
}, []);
return <button onClick={onRemove}>x</button>;
}
// Click x — what logs in order?
Hint
Cleanup runs on unmount after mount.
Explanation
On mount, "mount" logs. When the button is clicked, show becomes false, Child unmounts, and the cleanup function runs, logging "cleanup". Order: mount (on render), cleanup (on unmount).
Related Resources
Related Lessons
- useEffect
Learn useEffect.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.