What are composables? Write one and compare it with mixins.
A composable is a function that uses the Composition API to encapsulate and reuse stateful logic. By convention its name starts with use. It can create refs, computed values, watchers and lifecycle hooks, and returns what the component needs. Each call creates its own state (unless the state is created outside the function, which makes it shared).
Why not mixins
Mixins (Vue 2 / Options API) merged options into the component, which caused:
- Unclear origin: which mixin provided
this.loading? - Name collisions between mixins.
- Implicit coupling: mixins relying on each other's properties.
Composables fix all three: you explicitly destructure what you use, can rename it, and pass data in as arguments.
Good practices
- Accept refs, getters or plain values as arguments and normalise them with
toValue()(Vue 3.3+), so the composable reacts to changes. - Return an object of refs so callers can destructure.
- Clean up side effects with
onUnmountedor watcher cleanup. - VueUse is a large library of ready-made composables (
useLocalStorage,useFetch,useMediaQuery,useIntersectionObserver).
Example
// useFetch.js
import { ref, watchEffect, toValue } from 'vue';
export function useFetch(url) {
const data = ref(null);
const error = ref(null);
const loading = ref(false);
watchEffect(async onCleanup => {
const controller = new AbortController();
onCleanup(() => controller.abort());
loading.value = true;
error.value = null;
try {
const res = await fetch(toValue(url), { signal: controller.signal }); // tracks url if it is a ref or getter
if (!res.ok) throw new Error(`HTTP ${res.status}`);
data.value = await res.json();
} catch (e) {
if (e.name !== 'AbortError') error.value = e;
} finally {
loading.value = false;
}
});
return { data, error, loading };
}<script setup>
import { useFetch } from './useFetch';
const props = defineProps({ id: Number });
const { data: user, loading, error } = useFetch(() => `/api/users/${props.id}`);
</script>
<template>
<p v-if="loading">Loading…</p>
<p v-else-if="error">{{ error.message }}</p>
<h2 v-else>{{ user?.name }}</h2>
</template>Follow-up questions interviewers ask
Try answering each one before you open it.
Where must composables be called?
Synchronously inside <script setup> or setup() (or inside another composable called there), so lifecycle hooks and watchers can register on the current component instance. Calling one after an await or inside an event handler loses the instance, and hooks will warn or leak.