How to Use Lifecycle Hooks in Vue
As the creator of CoreUI and with over 25 years of Vue.js development experience, I’ll show you how to effectively use lifecycle hooks to control component behavior at different stages.
Vue lifecycle hooks are special methods that allow you to execute code at specific points in a component’s lifecycle, from creation to destruction.
<template>
  <div>
    <h2>{{ title }}</h2>
    <p>Count: {{ count }}</p>
    <button @click="increment">Increment</button>
    <div ref="chartContainer"></div>
  </div>
</template>
<script setup>
import { ref, onMounted, onUpdated, onUnmounted, onBeforeMount, onBeforeUpdate, onBeforeUnmount } from 'vue'
// Reactive data
const title = ref('Lifecycle Demo')
const count = ref(0)
const chartContainer = ref(null)
let timer = null
let chart = null
// Before component is mounted
onBeforeMount(() => {
  console.log('Before Mount: Component is about to be mounted')
  // Good for: Setup that doesn't require DOM access
})
// After component is mounted (DOM is available)
onMounted(() => {
  console.log('Mounted: Component is mounted')
  // Good for: DOM manipulation, API calls, third-party library initialization
  // Initialize third-party chart library
  if (chartContainer.value) {
    chart = initializeChart(chartContainer.value)
  }
  // Start a timer
  timer = setInterval(() => {
    console.log('Timer tick')
  }, 5000)
  // Fetch initial data
  fetchUserData()
})
// Before component updates
onBeforeUpdate(() => {
  console.log('Before Update: Component is about to update')
  // Good for: Accessing the current state before changes
})
// After component updates
onUpdated(() => {
  console.log('Updated: Component has updated')
  // Good for: DOM operations after data changes
  // Update chart with new data
  if (chart && count.value > 0) {
    chart.updateData(count.value)
  }
})
// Before component is unmounted
onBeforeUnmount(() => {
  console.log('Before Unmount: Component is about to be destroyed')
  // Good for: Cleanup preparations
})
// After component is unmounted
onUnmounted(() => {
  console.log('Unmounted: Component is destroyed')
  // Good for: Cleanup (timers, subscriptions, event listeners)
  // Clear timer
  if (timer) {
    clearInterval(timer)
  }
  // Destroy chart
  if (chart) {
    chart.destroy()
  }
  // Remove global event listeners
  window.removeEventListener('resize', handleResize)
})
// Methods
const increment = () => {
  count.value++
}
const fetchUserData = async () => {
  try {
    const response = await fetch('/api/user')
    const data = await response.json()
    console.log('User data loaded:', data)
  } catch (error) {
    console.error('Failed to fetch user data:', error)
  }
}
const initializeChart = (container) => {
  // Initialize chart library
  return {
    updateData: (newValue) => {
      console.log('Updating chart with:', newValue)
    },
    destroy: () => {
      console.log('Chart destroyed')
    }
  }
}
const handleResize = () => {
  console.log('Window resized')
}
// Set up global event listener in mounted
onMounted(() => {
  window.addEventListener('resize', handleResize)
})
</script>
The main lifecycle hooks are: onMounted (DOM available, ideal for API calls and third-party libraries), onUpdated (after reactive data changes), onUnmounted (cleanup), onBeforeMount/Update/Unmount (preparatory phases). Use onMounted for DOM manipulation and data fetching, onUpdated sparingly as it runs after every reactive update, and onUnmounted for essential cleanup to prevent memory leaks.
Best Practice Note:
In CoreUI components, we strategically use lifecycle hooks for chart initialization in onMounted, data synchronization in onUpdated, and cleanup in onUnmounted. This pattern ensures our components integrate seamlessly with third-party libraries while maintaining optimal performance and preventing memory leaks.
 Łukasz Holeczek
    Łukasz Holeczek
  



 
         
       
       
      