💚 Vue.js Intermediate

What is the Composition API and how do composables work?

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.