--- title: Register Lifecycle Hooks Synchronously During Setup impact: HIGH impactDescription: Asynchronously registered lifecycle hooks will never execute type: capability tags: [vue3, composition-api, lifecycle, onMounted, onUnmounted, async, setup] --- # Register Lifecycle Hooks Synchronously During Setup **Impact: HIGH** - Lifecycle hooks registered asynchronously (e.g., inside setTimeout, after await) will never be called because Vue cannot associate them with the component instance. This leads to silent failures where expected initialization or cleanup code never runs. In Vue 3's Composition API, lifecycle hooks like `onMounted`, `onUnmounted`, `onUpdated`, etc. must be registered synchronously during component setup. The hook registration doesn't need to be lexically inside `setup()` or ` ``` ```javascript // CORRECT: Hook in external function called synchronously from setup import { onMounted, onUnmounted } from 'vue' function useWindowResize(callback) { // This is fine - it's called synchronously from setup onMounted(() => { window.addEventListener('resize', callback) }) onUnmounted(() => { window.removeEventListener('resize', callback) }) } export default { setup() { // Composable called synchronously - hooks will be registered useWindowResize(handleResize) } } ``` ## Multiple Hooks Are Allowed ```javascript // CORRECT: You can register the same hook multiple times import { onMounted } from 'vue' export default { setup() { // Both will run, in order of registration onMounted(() => { initializeA() }) onMounted(() => { initializeB() }) } } ``` ## Reference - [Vue.js Lifecycle Hooks](https://vuejs.org/guide/essentials/lifecycle.html) - [Composition API Lifecycle Hooks](https://vuejs.org/api/composition-api-lifecycle.html)