Thuta Learning
IntermediateWeb Developmentbeginner

Lifecycle Hooks

Relax. We'll talk through this in plain words — no textbook voice.

What you'll walk away with

  • Understand when mounting and unmounting happen
  • Write cleanup logic

Let's break it down simply

Every component passes through create, mount, update, and unmount stages. Run any code that needs the DOM inside onMounted. Clean up timers, event listeners, and subscriptions in onUnmounted.

vue
<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
const width = ref(0)
const measure = () => { width.value = window.innerWidth }

onMounted(() => {
  measure()
  window.addEventListener('resize', measure)
})
onUnmounted(() => window.removeEventListener('resize', measure))
</script>

<template><p>Viewport: {{ width }}px</p></template>
You should see
Viewport: 1280px

Try it yourself

Write a timer component that increments every second, and clear the interval when it unmounts.

Lifecycle HooksVue.js

Easy traps

  • Not cleaning up event listeners
  • Accessing a DOM element inside setup before it's actually mounted

Exercise

Write a timer component that increments every second, and clear the interval when it unmounts.

You'll know it worked when: Viewport: 1280px