What are composables in Vue?
IntermediateVue interview questionBy UIRound, updated 17 November 2026
Short answer
A composable is a plain function that uses Vue's Composition API, such as ref, computed, watch and lifecycle hooks, to package stateful logic so several components can reuse it. By convention its name starts with use, it is called inside setup or <script setup>, and it returns an object of refs. Each component that calls it gets its own state, and any listeners it registers are cleaned up with the component.
A first composable: useMouse
// composables/useMouse.js
import { ref, onMounted, onUnmounted } from "vue";
export function useMouse() {
const x = ref(0);
const y = ref(0);
function update(event) {
x.value = event.pageX;
y.value = event.pageY;
}
onMounted(() => window.addEventListener("mousemove", update));
onUnmounted(() => window.removeEventListener("mousemove", update));
return { x, y };
}<script setup>
import { useMouse } from "@/composables/useMouse";
const { x, y } = useMouse();
</script>
<template>Mouse at {{ x }}, {{ y }}</template>Three things make this work. The refs are created inside the function, so every call gets fresh state rather than a shared global. onMounted and onUnmounted attach to whichever component is running setup at that moment, so the listener is removed when that component goes away. And the function returns refs, so the template stays reactive after destructuring.
A data composable: useFetch
Composables often accept reactive input. Accept a ref, a getter or a plain value, and normalise it with toValue() (Vue 3.3+). Reading it inside watchEffect means the fetch reruns whenever the input changes.
// composables/useFetch.js
import { ref, shallowRef, watchEffect, toValue } from "vue";
export function useFetch(url) {
const data = shallowRef(null);
const error = shallowRef(null);
const loading = ref(false);
watchEffect((onCleanup) => {
const controller = new AbortController();
onCleanup(() => controller.abort()); // runs before the next fetch and on unmount
loading.value = true;
error.value = null;
fetch(toValue(url), { signal: controller.signal })
.then((res) => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
})
.then((json) => { data.value = json; })
.catch((err) => { if (err.name !== "AbortError") error.value = err; })
.finally(() => { if (!controller.signal.aborted) loading.value = false; });
});
return { data, error, loading };
}<script setup>
import { useFetch } from "@/composables/useFetch";
const props = defineProps({ userId: String });
const { data: user, error, loading } = useFetch(() => `/api/users/${props.userId}`);
</script>Passing a getter keeps the link to props.userId. When the prop changes, the effect reruns, the cleanup aborts the old request, and a slow old response can never overwrite newer data. Watchers created during setup are stopped automatically when the component unmounts, so there is nothing else to clean up. shallowRef is used because the response is replaced as a whole, so deep reactivity on it would be wasted work. How refs and effects track dependencies is explained in How does reactivity work in Vue 3?.
Conventions that matter
- Name it
useSomething. It tells readers the function must be called duringsetupand may register hooks. - Return a plain object of refs, not a
reactive()object. Destructuring a reactive object breaks reactivity; destructuring refs does not. A caller who prefersmouse.xsyntax can wrap the result inreactive(). - Accept refs, getters or values and read them with
toValue()inside awatch,watchEffectorcomputed, so the composable reacts to changes. - Call it synchronously at the top level of
<script setup>orsetup(). Lifecycle hooks andinjectneed the current component instance, which only exists during that synchronous run.<script setup>restores the instance after a top-levelawait, but a call inside asetTimeoutor a.thencallback will fail. - Clean up what you start: event listeners, timers, observers, sockets. Use
onUnmounted, or theonCleanupcallback of a watcher. - Guard browser APIs for server rendering.
onMountedonly runs in the browser, so add DOM listeners there rather than at the top of the function.
Composables vs mixins
Composables replaced mixins as the recommended way to share logic, and the reasons are a common interview question.
| Mixins (Options API) | Composables | |
|---|---|---|
| Where values come from | Merged into this; unclear which mixin added what |
Explicit: const { x } = useMouse() |
| Name clashes | Two mixins defining loading overwrite each other |
Rename on destructure: const { loading: userLoading } = useFetch(...) |
| Passing arguments | Not possible directly | Ordinary function parameters, including refs |
| Composing | Mixins cannot easily use each other | A composable can call other composables |
| TypeScript | Weak inference through this |
Normal function inference |
The wider move from data and methods to setup is covered in Composition API vs Options API. Composables can still be used from an Options API component by calling them in a setup() option.
Composables vs React custom hooks
They look alike, but the runtime model is different. A React hook runs on every render, so it depends on call order, needs dependency arrays, and can capture stale values in closures. A Vue composable runs once per component instance, in setup. Reactivity tracks dependencies by itself, so there are no dependency arrays and no rule that it must run in the same order on each render, though it must still run synchronously during setup. The React side is in What are custom hooks in React?.
When not to write a composable
A composable that holds no reactive state and registers no hooks is just a utility function; drop the use prefix. If several components must share the same state instance, not just the same logic, a composable that creates state on each call is the wrong tool. Use a store such as Pinia, or provide and inject for a subtree.
Practise it
Implement Vue's computed() and watch() and Build Vue 3's reactive(), ref() and effect() show what a composable is built on, including onCleanup. Implement useFetch() with loading, error, and cancellation and Build everyday custom hooks are the React versions of the same reusable logic; writing both is a good way to feel the difference. Build a typeahead with caching and keyboard support splits neatly into composables.
Common follow-up questions
Do two components calling the same composable share state?
No, if the refs are created inside the function: each call makes new ones. If you create the refs outside the function, at module level, every caller shares them, which is a simple global store but is unsafe with server rendering, where one module instance serves many requests.
Can I use a composable outside a component?
Only parts of it. Plain ref and computed work anywhere, but lifecycle hooks and inject warn or fail without an active component instance. Libraries that need this use effectScope() to collect and later stop effects created outside components.
Why return refs instead of reactive objects?
So callers can destructure. const { x } = reactive({ x: 1 }) copies the current value and loses reactivity; const { x } = { x: ref(1) } keeps a live ref.
Where can I find ready-made composables?
VueUse is the widely used collection, with composables for the mouse, storage, media queries, intersection observers and much more. Reading its source is also a good way to learn the conventions.
Mistakes to avoid
Calling a composable inside a callback or after a timeout, where there is no current instance
Returning a
reactiveobject and having callers destructure itReading
toValue(input)once at the top of the composable, so it never reacts to later changesForgetting to remove listeners or abort requests on unmount
Defining state at module level by accident and sharing it between every component and every server request
Sources
Practise it in code
Interviewers rarely stop at the definition. These questions open in an editor with tests.
- Implement Vue's
computed()andwatch(): lazy cached getters, deep and immediate watchers, andonCleanupHard55 min - Build Vue 3's
reactive(),ref()andeffect()with Proxy: per-key tracking, lazy deep proxies and arraysHard60 min - Implement
useFetch()with loading, error, and cancellationMedium35 min - Build everyday custom hooks:
useToggle,useWindowSize,useOnlineStatusanduseCopyToClipboardMedium35 min - Build a typeahead/autocomplete with caching and keyboard supportMedium45 minFree