The need for composition API in Vue
Tags: vue, vuex, javascript, composition
Published: 2020-02-20 04:23:28

Well, Presently in Vue world, The hot🔥 topic is the Composition API, a function-based API introduced in Vue 3.0. In this article, We will learn what was the need for this new API and then how to use function-based API. I try to explain it in as much simple as I can to understand it for beginners also.

This article summarises the need for Composition API described in [#RFC](https://github.com/vuejs/rfcs/pull/42) & some examples.

So, Let's start 💻

Before we deep dive, There is no need to panic that the composition API will change the Vue drastically. Composition API is add-ons to the existing feature hence there are no breaking changes going into Vue 3.0
Moreover, the Vue team has created a plugin ([vue-composition](https://github.com/vuejs/composition-api)) which is compatible with Vue 2.x.

Let's see some questions first!


### What was the need for composition API?

 - As popularity increases for Vue day by day, People started to adopt Vue for large & Enterprise level application too. Due to which there were many cases where components for such applications grow gradually with the time and there is the moment when It was hard to maintain & read using Single File component architect. Hence the need for braking component in a logical manner arises and with Vue's existing API this was not possible. 

 - Instead of adding in another new concept, Composition APIs are proposed which basically expose Vue's core capabilities - such as creating and observing reactive state - as standalone functions and this API helps to write clean and reusable code among multiple components.


### What were the drawbacks of the alternative approaches that Vue has?

 - Before the introduction of the new API, Vue has other alternatives that offer reusability among components such as mixins, HOC(High order component), scoped slot but with all approaches comes with their own shortcomings due to which they are not widely used.

Mixins - It was hard to maintain once the app has some numbers of mixins. The developer needs to visit each mixin to see data is coming from which mixin.

HOC - This pattern doesn't go well with the Vue SFC approach, thus it is not widely recommended or popular to use among Vue developers.

Scoped slot - Even though slot hides the drawbacks of other concepts can't but with this approach, the developer ended up having a lot of reusable components and putting more and more login in Template which was again hard to maintain in longtime.


Kudos to Vue Team 👏


In Simple words, composition API helps to

1. Use low-level APIs of Vue which was not the case with Vue 2.x
2. Efficiently Organise and Write reusable code, as API is function-based.
3. Improves code readability by separating shared logic to functions.
4. Achieve code separation & DRY principle.
5. Use TypeScript better with Vue application.

Note: As Vue is very easy to start, so is the composition API.

Let's build one simple app to go through the API.

1) Import vue-composition plugin

```
npm install @vue/composition-api --save
```

2) Install plugin to the Vue app before importing any other APIs. The idea to register it before any other plugin is that composition API can be used in other plugins just as it is a built-in feature of Vue.

```
import VueCompositionApi from '@vue/composition-api';

Vue.use(VueCompositionApi);
```

3) Using composition API, Let's create a small functionality to understand the API better. Create a new folder, called `composition-fns` and create a file called `toggle.js`

Here, we are importing ref from the API and using it we are declaring the variable isVisible and which has by default value false.

In addition to it, There is a method called `toggle` which is responsible
for toggling the value of isVisible. 

```
import { ref } from "@vue/composition-api";

export const useToggle = () => {
  const isVisible = ref(false);

  const toggle = () => {
    return (isVisible.value = !isVisible.value);
  };

  return {
    isVisible,
    toggle
  };
};

```

4) At first, Import the `useToggle` function and then to use the above composition API in a component, API provides `setUp()` function. This setup function includes **data, methods, computed & watcher** object of the Vue component. 

Since here we're using the useToggle composition fn, we can destructure the values and return it using setup method in order to use it for the template.

```
import { useToggle } from "./composition-fn/toggle";
setup() {
  const { isVisible, toggle } = useToggle();
  // expose to template
  return {
    isVisible,
    toggle
  };
}
```
The `setUp` function can have two arguments. 
1. props - properties passed to the components and they are reactive since any change in props which results in re-render of the component.
2. context - which has selected properties which was earlier passed to component using `this`.

Context is having below functions/properties

```
context.refs
context.emit
context.attrs
context.slots
```

As `setUp` function is heart of composition API, It is very crucial to understand it.


5) In the end, Template is consists of the button and div to show and hide the toggle value.

```
<div>{{ isVisible }}</div>
<button type="button" @click="toggle">
  {{isVisible ? 'hide' : 'show' }} Toggle
</button>
```

Here is working [codesandbox](https://codesandbox.io/s/composition-api-4j9rn)

I hope this helps you to get started with composition API and journey towards Vue 3.0! 

Wish you good luck 😃