JAVASCRIPT

Managing Side Effects with Vue 3 Composition API Lifecycle Hooks

Learn to use `onMounted`, `onUnmounted`, `onUpdated`, and other Vue 3 Composition API lifecycle hooks to manage component side effects cleanly and effectively.

<script setup>
import { ref, onMounted, onUnmounted, onUpdated } from 'vue';

const count = ref(0);
let intervalId = null;

// Called after the component has been mounted to the DOM.
// Perfect for fetching data, setting up subscriptions, or DOM manipulations.
onMounted(() => {
  console.log('Component Mounted! Count is:', count.value);
  intervalId = setInterval(() => {
    count.value++;
  }, 1000);
  console.log('Interval started.');
});

// Called after the component has been unmounted from the DOM.
// Essential for cleaning up side effects to prevent memory leaks.
onUnmounted(() => {
  clearInterval(intervalId);
  console.log('Component Unmounted! Interval cleared.');
});

// Called after the component has updated its DOM tree.
// Useful for performing operations after a reactive state change reflects in the DOM.
onUpdated(() => {
  console.log('Component Updated! New count is:', count.value);
  // Avoid modifying reactive state directly here to prevent infinite update loops
});

// Other less common but available hooks:
// onBeforeMount(() => { console.log('Before Mount'); });
// onBeforeUpdate(() => { console.log('Before Update'); });
// onBeforeUnmount(() => { console.log('Before Unmount'); });
// onErrorCaptured((err, instance, info) => { console.error('Error captured:', err, info); return false; });
// onRenderTracked((e) => { console.log('Render tracked:', e); }); // For debugging reactivity
// onRenderTriggered((e) => { console.log('Render triggered:', e); }); // For debugging reactivity
</script>

<template>
  <div>
    <h1>Vue 3 Lifecycle Hooks Example</h1>
    <p>Count: {{ count }}</p>
  </div>
</template>
How it works: Vue 3's Composition API provides a set of functions that allow you to hook into a component's lifecycle from within the `setup` function. `onMounted` runs once the component is inserted into the DOM, making it ideal for initial data fetching or DOM-related setup. `onUnmounted` is called just before a component is removed from the DOM, crucial for cleanup tasks like clearing timers or unsubscribing from events to prevent memory leaks. `onUpdated` is triggered after a component's reactive state has changed and its DOM has been re-rendered, useful for actions that need to happen after the view is updated.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs