Since Vue 3, there has been a term that’s being used, called a composable and if you’ve ever used Nuxt, you’ll know that Nuxt 3 has a dedicated folder called composables, and whatever you put in there will be auto-imported and be ready to use as a composable, but what is actually a composable, is any function a composable, or is there a catch?
According to the Vue Documentation, a composable is a function that leverages Vue’s Composition API to encapsulate and reuse stateful logic, now the emphasis here lies on stateful logic.
We frequently need to reuse logic for repetitive operations while developing frontend applications. For example, we extract a reusable function in case we need to format dates in many locations. Stateless logic is encapsulated in this formatter function, which accepts input and outputs the desired result right away. Maybe you know date-fns and lodash, two of the many libraries available for reusing stateless logic.
Stateful logic, on the other hand, deals with managing state that varies over time. Tracking the mouse’s current location on a page would be a basic example. More sophisticated logic, like touch gestures or database connection status, may also be used in real-world situations.
This alone helps us understand, what can be considered as composable, and what not. So, if you’re writing a function, that’s stateless, you can just put it into a utils folder. Right? Well, yes but at this stage, I still find this explanation, not very verbose.
This is the real deal and the real determinator, to consider a function, as a composable. It has to use, Vue’s Composition API. After all, a composable, can be called within the setup funciton, other composables and some lifecycle hooks. If you function fulfills one of these points, consider that magical function as a composable!
Actually, not really. That pretty much sums it up, your function can be considered as a composable if:
That’s it; if you function checks these, then you’re good to go and can happily call it a composable.