Lifecycle Hooks
Composition API lifecycle hooks include onMounted, onUpdated, onUnmounted, and more. This lesson covers practical patterns, syntax, and mistakes to avoid.
Component Lifecycle Composition API lifecycle hooks include onMounted, onUpdated, onUnmounted, and more.
Use them to integrate native listeners and third-party libraries.
import { onMounted, onUnmounted } from 'vue'
onMounted(() => window.addEventListener('resize', onResize))
onUnmounted(() => window.removeEventListener('resize', onResize)) Add/remove a listener safely.
Map from Options mounted → onMounted, beforeUnmount → onBeforeUnmount Prefer Composition API + script setup. Use computed for derived UI. Keep side effects intentional. Practice in a small Vite app. Lifecycle Hooks Cheatsheet Quick reference for patterns covered in this lesson.
Item Example Purpose onMounted DOM ready Common onBeforeUnmount cleanup soon Common onUnmounted cleaned Common onUpdated after patch Rare suspense async setup Advanced keep-alive activated Cached
Prefer Effects Discipline Overusing onUpdated is usually a smell.
Common Mistakes Forgetting to remove listeners. DOM measurement before mount. Key Takeaways Lifecycle Hooks is important in Vue apps. Practice in SFCs. Prefer clear naming. Check Vue docs for details.
Pro Tip
If you need DOM nodes, wait until onMounted.
watchEffect Go to next item