Understanding Vue Composables (Hooks) and Their Usage
Vue’s reusable logic pattern, called Composables, are functions built with the Composition API that encapsulate reactive state via ref and lifecycle hooks, follow a use‑prefix naming convention, and let developers like the mouse‑tracker example share stateful behavior across components cleanly.
During a chat the author realized that the term people use in Vue for reusable logic is not "hooks" but Composables , which are functions built with the Vue Composition API.
In general, a hook is a callback mechanism (e.g., git hooks). React introduced React Hooks as functions whose names start with use . Vue does not have a native hook concept, but it provides a similar pattern through Composables.
A Composable is a function that encapsulates stateful logic using Vue’s reactive primitives (e.g., ref ) and lifecycle hooks. Its name should start with use , and it typically returns data wrapped by ref so that the consumer can react to changes.
Below is a direct implementation of a mouse‑tracker inside a component using the Composition API:
<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
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))
</script>
<template>Mouse position is at: {{ x }}, {{ y }}</template>The logic consists of three steps: create reactive refs, attach/detach the mouse‑move listener in the component’s lifecycle, and update the refs inside the handler.
// mouse.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 can now reuse this logic by importing the composable:
<script setup>
import { useMouse } from './mouse.js'
const { x, y } = useMouse()
</script>
<template>Mouse position is at: {{ x }}, {{ y }}</template>Key takeaways: use ref for reactive state inside composables, and Vue lifecycle hooks work normally within them, enabling clean reuse of logic across components.
Java Tech Enthusiast
Sharing computer programming language knowledge, focusing on Java fundamentals, data structures, related tools, Spring Cloud, IntelliJ IDEA... Book giveaways, red‑packet rewards and other perks await!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.