--- title: Call Composables Only in Setup Context Synchronously impact: HIGH impactDescription: Composables called outside setup context or asynchronously fail to register lifecycle hooks and may cause memory leaks type: gotcha tags: [vue3, composables, composition-api, setup, async, lifecycle] --- # Call Composables Only in Setup Context Synchronously **Impact: HIGH** - Composables must be called synchronously within ` ``` **Correct:** ```vue ``` ## Exception: Calling in Lifecycle Hooks Composables CAN be called inside lifecycle hooks because Vue maintains the component context: ```vue ``` ## Special Case: Async Setup in ` ``` ## Why This Matters When you call a composable, Vue needs to know which component instance to associate it with. This association happens through an internal "current instance" that's only set during synchronous setup execution. ```javascript // Inside a composable export function useFetch(url) { const data = ref(null) // These need the current component instance! onMounted(() => { /* ... */ }) onUnmounted(() => { /* cleanup */ }) // If called outside setup context, Vue can't find the instance // and these hooks are silently ignored return { data } } ``` ## Reference - [Vue.js Composables - Usage Restrictions](https://vuejs.org/guide/reusability/composables.html#usage-restrictions) - [Vue.js Composition API - Setup Context](https://vuejs.org/api/composition-api-setup.html)