We use cookies to enhance your experience on the site
CodeWorlds

Lifecycle Hooks - Component Lifecycle

Dr. Nova explains: "Every NOVA LAB station module goes through phases: installation, startup, firmware updates, and eventually decommissioning. Vue components have an identical lifecycle - and you can execute code in each of these phases!"

Component Lifecycle Phases

A Vue component goes through several key phases:

  1. Creation - the component is initialized, reactive state is configured
  2. Mounting - the component is inserted into the DOM (becomes visible on the page)
  3. Updating - reactive data changes, DOM is updated
  4. Unmounting - the component is removed from the DOM

In each phase you can run code using lifecycle hooks - special functions called automatically by Vue.

onBeforeMount and onMounted

onMounted
is the most commonly used hook. It runs after the component has been inserted into the DOM:

1<template>
2  <div class="module-status">
3    <p>Status: {{ status }}</p>
4    <p>Data: {{ data }}</p>
5  </div>
6</template>
7
8<script setup>
9import { ref, onBeforeMount, onMounted } from 'vue'
10
11const status = ref('Initializing...')
12const data = ref(null)
13
14// Before mounting - DOM doesn't exist yet
15onBeforeMount(() => {
16  console.log('Component is about to mount')
17  status.value = 'Mounting...'
18})
19
20// After mounting - DOM is ready!
21onMounted(() => {
22  console.log('Component mounted in DOM')
23  status.value = 'Active'
24
25  // Typical use: fetching data from API
26  fetchModuleData()
27})
28
29async function fetchModuleData() {
30  const response = await fetch('/api/modules')
31  data.value = await response.json()
32}
33</script>

When to use

onMounted
:

  • Fetching data from API
  • Accessing DOM elements (
    document.querySelector
    , references)
  • Initializing external libraries (e.g., charts, maps)
  • Starting timers and intervals

onBeforeUnmount and onUnmounted

These hooks run when the component is being removed from the DOM. They serve for resource cleanup:

1<script setup>
2import { ref, onMounted, onBeforeUnmount, onUnmounted } from 'vue'
3
4const timer = ref(null)
5const seconds = ref(0)
6
7onMounted(() => {
8  // Start timer after mounting
9  timer.value = setInterval(() => {
10    seconds.value++
11  }, 1000)
12  console.log('Timer started')
13})
14
15onBeforeUnmount(() => {
16  // Before unmounting - component is still in DOM
17  console.log('Component is about to be removed')
18})
19
20onUnmounted(() => {
21  // Clean up timer so it doesn't run after component removal!
22  if (timer.value) {
23    clearInterval(timer.value)
24    console.log('Timer cleaned up')
25  }
26})
27</script>

Why is cleanup important? If you don't clear

setInterval
, the timer will keep running even after the component is removed from DOM, causing memory leaks.

onBeforeUpdate and onUpdated

These hooks react to reactive data changes and DOM updates:

1<script setup>
2import { ref, onBeforeUpdate, onUpdated } from 'vue'
3
4const count = ref(0)
5
6onBeforeUpdate(() => {
7  // Before DOM update
8  console.log('DOM is about to update')
9})
10
11onUpdated(() => {
12  // After DOM update
13  console.log('DOM updated, new value:', count.value)
14})
15</script>

These hooks are used less frequently - they're useful when you need to react to DOM changes (e.g., scroll position, animations).

Practical Example: Module with Data and Timer

1<template>
2  <div class="station-module" style="background: #0a0e27; color: #00ff88; padding: 1rem;">
3    <h3>Module: {{ moduleName }}</h3>
4    <p>Uptime: {{ uptime }}s</p>
5    <p>Status: {{ status }}</p>
6    <ul>
7      <li v-for="log in logs" :key="log">{{ log }}</li>
8    </ul>
9  </div>
10</template>
11
12<script setup>
13import { ref, onMounted, onUnmounted } from 'vue'
14
15const moduleName = ref('Oxygen Generator')
16const uptime = ref(0)
17const status = ref('Starting...')
18const logs = ref([])
19let intervalId = null
20
21onMounted(() => {
22  logs.value.push('System mounted')
23  status.value = 'Active'
24
25  // Timer updating uptime every second
26  intervalId = setInterval(() => {
27    uptime.value++
28  }, 1000)
29
30  logs.value.push('Timer started')
31})
32
33onUnmounted(() => {
34  // Cleanup on unmount
35  if (intervalId) {
36    clearInterval(intervalId)
37  }
38  console.log('Module shut down, resources released')
39})
40</script>

Hook Order - Summary

1Creation:       setup() → onBeforeMount → onMounted
2Update:         onBeforeUpdate → onUpdated
3Unmounting:     onBeforeUnmount → onUnmounted

Remember the two most important ones:

  • onMounted
    - fetching data, initialization (start)
  • onUnmounted
    - cleaning up timers, listeners (cleanup)
Go to CodeWorlds