The new Composition API caused a fair amount of controversy when it was first announced by the Vue team. But now that the dust has settled and we’ve had a chance to try the demo, most of us can see it has great potential.

But like every programming tool, we can expect it to have both benefits and drawbacks. So what I’m thinking about most now is not if to use it, but when to use it.

The RFC says that:

“the problems [the composition API] aims to address appear primarily in large scale applications”.

But is it of any use in smaller applications? Or should it perhaps be avoided there?

In this article, I’ll give you my thoughts and share a guiding principle that you may find useful.

Motivating example

In the RFC, a motivating example is given of a large component with many features that became unwieldy under the options API.

The RFC then shows how refactoring this component to use the composition API allowed the functionality to be organized by feature instead of by option thereby restoring readability.

Code organization example

While this example is perfectly illustrative of when the composition API is needed, it left me somewhat confused because this example component is atypically large and complex.

Will the same benefits be accrued with the smaller, “regular” components that I most commonly deal with? To answer this, I think it’s worth looking at the conditions under which a component gets so large and complex.

Component composition model

Along with reactivity, the component composition model is a defining characteristic of Vue.js.

While the docs don’t explicitly say so, there’s an implied aim to have a one-to-one relationship between a component and a “feature” in this model.

For example, a button-based component like the following will usually begin with one feature - to handle clicks it receives.

<template>
  <button @click="doStuff">Click me</button>
</template>

But this component could be designed, or unintentionally grow, to include multiple features. For example, what if we decided to make it so this button spawned a drop-down?

At first, we might add the drop-down into the template and component state, but then our understanding of the component composition model would kick in again and we’d be compelled to abstract the new feature into a sub-component thus restoring the one-to-one ratio of components/features.

<template>
  <button @click="doStuff">
    Click me
    <drop-down v-bind:some-prop="..." />
  </button>
</template>

#vue.js #composition api #components #design patterns #vue

When To Use The New Vue Composition API (And When Not To)
2.25 GEEK