Skip to content

QuizNot attempted

Cleanup on unmount

From the first render through clicking the "hide" button, what logs in total?
function App() {
const [show, setShow] = useState(true);
return (
<div>
{show && <Widget />}
<button onClick={() => setShow(false)}>{'hide'}</button>
</div>
);
}
function Widget() {
useEffect(() => {
console.log('mount');
return () => console.log('unmount');
}, []);
return <p>widget</p>;
}
1–4 to choose, Enter to submit
Show answer & explanation

Correct answer:

  • mount then unmount
  • Widget mounts on the first render (show is true), so its effect logs mount
  • the click sets show false, Widget leaves the tree, and React runs its cleanup: unmount.
  • Not 'mount only': unmounting always runs cleanups.
  • Not 'unmount only': the mount log already happened on the first render.
  • Not nothing: effects with [] still run once.