💚 Vue.js Beginner

What are Vue composables?

Why Interviewers Ask This

Interviewers use this question to quickly assess whether a candidate has the foundational knowledge required for Vue.js development. It reveals whether you understand the building blocks that more complex concepts rely on.

Answer

Composables are reusable functions that use Vue's Composition API to encapsulate and share stateful logic between components — the Vue 3 replacement for Vue 2 mixins. A composable is a plain JavaScript function (by convention prefixed with "use") that uses reactive primitives (ref, computed, watch, lifecycle hooks) internally. Example composable: // useFetch.js export function useFetch(url) { const data = ref(null); const loading = ref(true); const error = ref(null); async function fetchData() { loading.value = true; try { data.value = await (await fetch(url)).json(); } catch(e) { error.value = e; } finally { loading.value = false; } } onMounted(fetchData); return { data, loading, error, refetch: fetchData }; }. Using in a component: import { useFetch } from "./composables/useFetch"; const { data: users, loading, error } = useFetch("/api/users");. vs Mixins (Vue 2): mixins have unclear sources of data and name collisions (two mixins with the same property name). Composables have explicit returns — you always know where a value came from. Composables can accept parameters; mixins can't. Popular patterns: useLocalStorage, useEventListener, useMouse, useMediaQuery, useDebounce, useIntersectionObserver. VueUse (vueuse.org) is a collection of 200+ ready-made composables.

Common Mistake

Many candidates answer correctly but can't explain the 'why'. Always be prepared to justify your answer with a concrete example or use case from your Vue.js experience.