Back
VueMediumNew
What are composables and how do you write one?
Reusable stateful logic functions, usually named useX
Ideal Answer
A composable is a function that leverages the Composition API to encapsulate and reuse stateful logic across components. By convention, composables are named starting with use.
JavaScript
// 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 }
}
Components call it like a hook: const { x, y } = useMouse(). Composables replace the older mixin pattern with clearer, explicit data sources and no naming collisions.