Vue Tip: When You Should Use a Composable
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:
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:
Rule of thumb for composable functions
If your function does not manage any reactive state, doesn't register any lifecycle hooks or doesn't provide/inject anything, it is not a composable.
Finally, let's take a look at a good example of a composable:
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 X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:
Vue Tip: Mutate Your State Inside of the Provider Using Provide and Inject
When using reactive provide/inject values, it is recommended to keep any mutations to reactive state inside of the provider whenever possible.
Vue Tip: How I Write Class & Style Bindings
Styling your components in Vue.js can be done in multiple ways. One of the most common ways is to use the class attribute, especially if you are using a CSS framework like Tailwind. In combination with v-bind you can dynamically assign classes to your components.