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
MediumComplete 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>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
2Reactive State
Reactive RefsUpdating Refs in ScriptEvent Handler ArgumentsReactive ObjectsRecap: Reactive State5Conditions and Lists
Conditional BranchesShow without UnmountingRendering ListsStable List IdentityRecap: Conditions8Component Communication
Emitting EventsEvent PayloadsLifting Shared StateDefault and Named SlotsRecap: Shared Panel11Project: Community Board
Board StructureAdding Community Tasks6Working with Lists
Adding List ItemsRemoving by IdComputed Search ResultsCounts from ListsRecap: List Manager9Watchers and Lifecycle
Watching a RefWatching Object FieldsMounted DOM AccessCleaning Up on UnmountRecap: Activity Log