Menu
CoddyTech

Cleaning Up on Unmount

Part of the Fundamentals section of Coddy's Vue journey. Lesson 44 of 55.

Effects attached outside a component can outlive its DOM. Register a window listener when mounted and remove it when the component is unmounted, using the same function reference.

function handleResize() { console.log('resized'); }
onMounted(() => window.addEventListener('resize', handleResize));
onUnmounted(() => window.removeEventListener('resize', handleResize));

Removing a listener with a newly created arrow function does not match the registered function. A conditional component can mount again later, so missing cleanup causes old listeners to accumulate. Vue automatically stops setup-created watchers on unmount, but external listeners still need their own cleanup.

challenge icon

Challenge

Medium

Complete ResizeProbe.vue. Register a window resize listener in onMounted; its named handler calls the supplied record function prop. Remove the same handler in onUnmounted. The supplied parent can toggle the child and dispatch a real resize event. Its count must increase once per event while mounted and stay unchanged while the child is absent.

Try it yourself

<!doctype html><html><head><meta charset="UTF-8"><title>Vue practice</title></head><body><div id="app"></div><script type="module" src="./main.js"></script></body></html>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals