JAVASCRIPT
Managing Side Effects with Vue 3 Lifecycle Hooks
Utilize Vue 3's Composition API lifecycle hooks like `onMounted`, `onUnmounted`, and `onUpdated` to perform actions when a component is mounted, updated, or destroyed.
<script setup>
import { ref, onMounted, onUnmounted, onUpdated } from 'vue';
const counter = ref(0);
let intervalId = null;
onMounted(() => {
console.log('Component is mounted!');
// Example: Start an interval when the component mounts
intervalId = setInterval(() => {
counter.value++;
}, 1000);
});
onUpdated(() => {
console.log('Component updated. Counter:', counter.value);
// Example: Log whenever the component's reactive state changes and it re-renders
});
onUnmounted(() => {
console.log('Component is unmounted!');
// Example: Clear the interval to prevent memory leaks
if (intervalId) {
clearInterval(intervalId);
intervalId = null;
}
});
// Function to stop the counter manually
const stopCounter = () => {
if (intervalId) {
clearInterval(intervalId);
intervalId = null;
console.log('Counter stopped manually.');
}
};
</script>
<template>
<div>
<h1>Lifecycle Hook Example</h1>
<p>Counter: {{ counter }}</p>
<button @click="stopCounter">Stop Counter</button>
<p>Open your browser console to see lifecycle messages.</p>
</div>
</template>
How it works: This snippet demonstrates the use of Vue 3's Composition API lifecycle hooks. `onMounted` is used to execute code after the component has been mounted to the DOM, often for initial data fetching or setting up event listeners. `onUnmounted` is crucial for performing cleanup tasks, such as clearing timers or removing event listeners, to prevent memory leaks. `onUpdated` runs after the component has updated its DOM tree due to reactive state changes.