Skip to main content

What is the Composition API?

The Composition API is a modern way to write Vue 3 components that lets you organize logic by functionality, rather than by options (data, methods, computed...), as in the Options API.

In simpler terms:

The Composition API is a set of functions (ref, reactive, computed, watch, onMounted and others) that let you build a component's logic inside setup(), like a logic constructor.

It was created for better structuring of complex components and convenient code reuse.


How does the Composition API differ from the Options API?

In the Options API, code is split into sections:

js
export default { data() { ... }, methods: { ... }, computed: { ... }, mounted() { ... } }

As a result, logic related to a single task can end up scattered across different blocks.


In the Composition API, all related logic sits next to each other:

js
<script setup> import { ref, onMounted } from 'vue' const count = ref(0) function increment() { count.value++ } onMounted(() => { console.log("Component mounted") }) </script>

The main idea of the Composition API

Group related logic into functions, instead of scattering it across different sections of a component.

This makes it easier to:

  • maintain large components
  • reuse logic
  • create your own hooks (useSomething())
  • read and understand the code

Key functions of the Composition API

Reactivity

  • ref()
  • reactive()
  • computed()
  • watch()
  • watchEffect()

Lifecycle

  • onMounted()
  • onUpdated()
  • onUnmounted()
  • onBeforeMount()
  • onActivated() / onDeactivated()

Structuring code

  • setup()
  • <script setup> (recommended syntax)

Example: a counter with the Composition API

vue
<script setup> import { ref } from 'vue' const count = ref(0) function increment() { count.value++ } </script> <template> <button @click="increment">Count: {{ count }}</button> </template>

When is the Composition API most useful?

1. Large components

It's easier to split logic into "modules".

2. Reusable logic (composables)

You can write your own hooks:

js
function useCounter() { const count = ref(0) const inc = () => count.value++ return { count, inc } }

3. Better control over reactivity

You can write flexible watchers, computed values, and side effects.

4. More readable complex components

No need to jump between sections.

5. TypeScript friendliness

The Composition API was designed with TS in mind.


What is <script setup>?

Vue 3.2 added a simplified syntax:

vue
<script setup> import { ref } from 'vue' const msg = ref('Hello') </script>

It is:

  • shorter
  • faster
  • automatically does everything setup() normally did

And it is the recommended way to write components.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.