Lifecycle and DOM
Running Code on Unmount
The component lifecycle lets you run tasks when a component is removed, commonly to clean up previously created effects.
Example
Removing a window event listener when a component is removed.
VueonUnmounted
<script setup lang="ts">
import { onMounted, onUnmounted } from 'vue'
function handleResize() {
console.log('Window resized')
}
onMounted(() => {
window.addEventListener('resize', handleResize)
})
onUnmounted(() => {
window.removeEventListener('resize', handleResize)
})
</script>
<template>
<p>Listening for resize events</p>
</template>
It uses onUnmounted to remove the listener after the component has been unmounted.
ReactuseEffect cleanup
import { useEffect } from 'react'
function Status() {
useEffect(() => {
function handleResize() {
console.log('Window resized')
}
window.addEventListener('resize', handleResize)
return () => {
window.removeEventListener('resize', handleResize)
}
}, [])
return <p>Listening for resize events</p>
}
It returns a cleanup function from useEffect to remove the listener when the Effect ends.
AngularngOnDestroy
import { Component } from '@angular/core'
@Component({
selector: 'app-status',
standalone: true,
template: `<p>Listening for resize events</p>`,
})
export class StatusComponent {
handleResize = () => {
console.log('Window resized')
}
ngOnInit() {
window.addEventListener('resize', this.handleResize)
}
ngOnDestroy() {
window.removeEventListener('resize', this.handleResize)
}
}
It defines ngOnDestroy to remove the listener just before Angular destroys the component.
