What is the Composition API and how do composables work?
Why Interviewers Ask This
This question targets practical, hands-on experience with Vue.js. Interviewers want to see if you've worked with these concepts in real projects, not just read about them. Strong answers include concrete examples.
Answer
The Composition API is a set of reactive primitives and lifecycle hooks that can be organized in a setup() function or <script setup>. Composable pattern: a composable is a function that uses Composition API internally to encapsulate stateful, reusable logic. It can accept reactive arguments and return reactive state. Advanced composable example — useIntersectionObserver: export function useIntersectionObserver(target, options = {}) { const isIntersecting = ref(false); let observer; onMounted(() => { observer = new IntersectionObserver((entries) => { isIntersecting.value = entries[0]?.isIntersecting ?? false; }, options); if (target.value) observer.observe(target.value); }); onUnmounted(() => observer?.disconnect()); return { isIntersecting }; }. Usage: const el = ref(null); const { isIntersecting } = useIntersectionObserver(el); <div ref="el" :class="{ visible: isIntersecting }">. Accepting reactive arguments: composables should use toValue() (Vue 3.3+) or isRef() to handle both plain values and refs as arguments: const url = computed(() => `/api/${toValue(id)}`);. Side-effect cleanup: always clean up in onUnmounted. async composables: can use await but the async suspense integration requires special handling. Testing composables: test in isolation — create a test component or use withSetup(fn) utility.
Pro Tip
Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a Vue.js codebase.
More Vue.js Questions
View all →- Intermediate What is Vue's reactivity in depth — ref vs reactive?
- Intermediate What are Vue 3 Teleport and Suspense?
- Intermediate What is Vue's virtual DOM and how does the diffing algorithm work?
- Intermediate What is Vue's reactivity with watchEffect and its nuances?
- Intermediate What is Vue's component communication patterns?