Vue Composables
A composable is a function that uses the Composition API to encapsulate and reuse stateful logic. By convention its name starts with use: useMouse(), useCounter(), useFetch(). Inside, it creates refs, computed values, watchers and lifecycle hooks — exactly as you would in setup() — and returns what callers need.
// useCounter.js
import { ref, computed } from 'vue';
export function useCounter(start = 0) {
const count = ref(start);
const isEven = computed(() => count.value % 2 === 0);
const inc = () => count.value++;
const reset = () => { count.value = start; };
return { count, isEven, inc, reset };
}Any component can now call useCounter() and gets its own independent state.
A first composable
<div id="app">
<p>Apples: {{ apples.count }} {{ apples.isEven ? '(even)' : '(odd)' }}
<button @click="apples.inc">+</button> <button @click="apples.reset">reset</button></p>
<p>Pears: {{ pears.count }}
<button @click="pears.inc">+</button> <button @click="pears.reset">reset</button></p>
</div>
<script type="module">
import { createApp, ref, computed, reactive } from 'vue';
function useCounter(start = 0) {
const count = ref(start);
const isEven = computed(() => count.value % 2 === 0);
const inc = () => count.value++;
const reset = () => { count.value = start; };
return { count, isEven, inc, reset };
}
createApp({
setup() {
// reactive() unwraps the refs, so the template can write apples.count
const apples = reactive(useCounter(3));
const pears = reactive(useCounter(10));
return { apples, pears };
}
}).mount('#app');
</script>Usually you destructure the result: const { count, inc } = useCounter(). That's safe because the composable returns refs, which keep their reactivity when passed around. (Here we wrapped each result in reactive() only so the template can group them as apples.count and pears.count.)
Composables with lifecycle hooks
Composables can register lifecycle hooks; they attach to the component that calls the composable. This makes "set up and clean up" logic reusable:
<style> .pad { height: 110px; background: #ecfdf5; display: grid; place-items: center; font-family: monospace; } </style>
<div id="app">
<div class="pad">mouse: {{ x }}, {{ y }} · window {{ width }}px wide · online: {{ online }}</div>
<button @click="show = !show">{{ show ? 'Unmount' : 'Mount' }} second tracker</button>
<mouse-label v-if="show"></mouse-label>
</div>
<script type="module">
import { createApp, ref, onMounted, onUnmounted } from 'vue';
// a tiny helper composable used by others
function useEventListener(target, event, handler) {
onMounted(() => target.addEventListener(event, handler));
onUnmounted(() => target.removeEventListener(event, handler));
}
function useMouse() {
const x = ref(0), y = ref(0);
useEventListener(window, 'mousemove', (e) => { x.value = e.clientX; y.value = e.clientY; });
return { x, y };
}
function useWindowWidth() {
const width = ref(window.innerWidth);
useEventListener(window, 'resize', () => { width.value = window.innerWidth; });
return { width };
}
function useOnline() {
const online = ref(navigator.onLine);
useEventListener(window, 'online', () => { online.value = true; });
useEventListener(window, 'offline', () => { online.value = false; });
return { online };
}
const app = createApp({
setup() {
return { ...useMouse(), ...useWindowWidth(), ...useOnline(), show: ref(true) };
}
});
app.component('mouse-label', {
setup() {
const { x, y } = useMouse();
onUnmounted(() => console.log('mouse-label removed its listener'));
return { x, y };
},
template: `<p>Second tracker: {{ x }}, {{ y }}</p>`
});
app.mount('#app');
</script>Composables can call other composables (useMouse uses useEventListener), so you build big behaviour out of small pieces.
Accepting refs as arguments
Good composables accept either plain values or refs/getters, and react when they change. toValue() (Vue 3.3+) normalises them, and watchEffect re-runs when the input changes:
<div id="app">
<p><input v-model="text" placeholder="Type to search"></p>
<p>{{ matches.length }} match(es): {{ matches.join(', ') }}</p>
<p>Debounced value: "{{ debounced }}"</p>
</div>
<script type="module">
import { createApp, ref, computed, watch, toValue } from 'vue';
function useDebounced(source, delay = 400) {
const value = ref(toValue(source));
let timer;
watch(() => toValue(source), (v) => {
clearTimeout(timer);
timer = setTimeout(() => { value.value = v; }, delay);
});
return value;
}
function useFilter(list, query) {
return computed(() => {
const q = toValue(query).toLowerCase();
return toValue(list).filter(item => item.toLowerCase().includes(q));
});
}
createApp({
setup() {
const text = ref('');
const debounced = useDebounced(text, 400);
const languages = ['JavaScript', 'TypeScript', 'Rust', 'Ruby', 'Python', 'Java'];
const matches = useFilter(languages, debounced);
return { text, debounced, matches };
}
}).mount('#app');
</script>Composables vs other reuse techniques
| Technique | Problem |
|---|---|
| Mixins (Options API) | Unclear where properties come from; name collisions |
| Renderless components | Extra component instances; logic tied to templates |
| Composables | Plain functions: explicit inputs/outputs, no collisions, easy to test |
Conventions
- Name them
useSomethingand put them insrc/composables/useSomething.js. - Return a plain object of refs (not a
reactive()), so callers can destructure. - Call them synchronously at the top of
setup()/<script setup>so hooks attach to the right component. - Clean up everything you start (listeners, timers, observers).
Tip: The community library VueUse offers 200+ ready-made composables (
useMouse,useLocalStorage,useFetch,useDark…). Read its source code — it's a great way to learn composable design.
Test yourself
What is a composable?
- A component without a template
- A function that uses the Composition API to encapsulate reusable stateful logic
- A CSS framework for Vue
- A Vue plugin
Two components both call useCounter(). Do they share the same count?
- Yes, always
- No, each call creates new state
- Only if they are siblings
- Only in production
Why should a composable return an object of refs rather than a reactive() object?
- Refs are faster
- So callers can destructure the result without losing reactivity
- reactive() is deprecated
- Templates can't read reactive objects