QA
Beginner LevelVue JS

What are the primary Vue 3 Composition API lifecycle hooks (onMounted, onUnmounted)?

❓ Interview Prompt: Explain Vue 3 lifecycle hooks: onMounted, onUnmounted, onUpdated, and component initialization timing.

Vue components go through a distinct lifecycle: creation, DOM mounting, state updating, and unmounting.

Composition API Hooks:

•
'onMounted()': Fired after the component has finished initial rendering and inserted its DOM nodes. Ideal for DOM measurements, window listeners, and initial API data fetching.
•
'onUpdated()': Fired after component reactive state changes and DOM updates re-render.
•
'onUnmounted()': Fired right after the component is destroyed and removed from the DOM. Essential for clearing timers ('clearInterval') and event listeners ('removeEventListener') to prevent memory leaks!

Code Implementation Example

javascript
import { ref, onMounted, onUnmounted } from 'vue';

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

onMounted(() => {
  console.log('Component mounted in DOM!');
  intervalId = setInterval(() => timerCount.value++, 1000);
});

onUnmounted(() => {
  console.log('Component unmounting. Cleaning up interval timer!');
  clearInterval(intervalId); // Prevents memory leak!
});
💡Managing side effects using onMounted and onUnmounted lifecycle hooks.
🎯 Interview Key Takeaway

Use onMounted for DOM access and API calls. Always clear timers and listeners in onUnmounted to prevent memory leaks.

#Lifecycle Hooks#onMounted#onUnmounted#Beginner
Back to all Vue JS Questions→

More Vue JS Interview Questions

Beginner LevelVue JS

What is the difference between Options API and Composition API in Vue 3?

Beginner LevelVue JS

What is the difference between ref() and reactive() in Vue 3?

Beginner LevelVue JS

What is the difference between computed properties, methods, and watch/watchEffect?