Vue Composables are a way to encapsulate logic in a reusable way and they are one of my favorite features of Vue 3.
They are a great way to share logic between components, but I often see them used in places where they are not needed. In this short tip, I will explain when you should use a composable and when you should not.
Let's take a look at the following code example:
export const useDate = (dateString: string) => {
const date = new Date(dateString)
const getFormattedDate = () => {
return date.toLocaleDateString()
}
return {
date,
getFormattedDate
}
}
What do you think, would you call this method a composable or not?
The answer is: No.
Let's take a look at the official documentation:
In the context of Vue applications, a "composable" is a function that leverages Vue's Composition API to encapsulate and reuse stateful logic.
The key part here is stateful logic which involves "managing state that changes over time". In our example, we are not using any reactive state, so this is not a composable. I would call it a utility/helper function.
Let's define a simple rule of thumb:
Finally, let's take a look at a good example of a composable:
import { ref, onMounted, onUnmounted } from 'vue'
export const useMouse = () => {
const x = ref(0)
const y = ref(0)
const update = (event) => {
x.value = event.pageX
y.value = event.pageY
}
onMounted(() => window.addEventListener('mousemove', update))
onUnmounted(() => window.removeEventListener('mousemove', update))
return { x, y }
}
This composable manages the mouse position and provides two reactive values x
and y
. It also registers and unregisters an event listener when the component is mounted and unmounted.
If you liked this Vue tip, follow me on BlueSky to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter :
Vue Tip: How I Write Class & Style Bindings
Vue Tip: Mutate Your State Inside of the Provider Using Provide and Inject