💚 Vue.js Intermediate

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.