Market LiveNIFTY25,259-0.16%SENSEX82,082.4+0.21%Gold 24K ₹12,098.38/g down302.9Silver ₹146.46/g down5.43
InsightforGeeks
VueJS

Vue 3 Composition API in Plain Words: ref, reactive and computed

insightforgeeks-editorial
16 Nov 2026
4 min read
Share:

The Composition API is the modern way to write Vue 3 components. With <script setup> it needs less code than the older Options API and lets you reuse logic easily. Here are the three building blocks you will use every day.

ref: a reactive value

ref wraps a single value so Vue can track changes. In the script you read and write it through .value; in the template Vue unwraps it for you.

<script setup>
import { ref } from 'vue'
const count = ref(0)
function increment() { count.value++ }
</script>

<template>
  <button @click="increment">Clicked {{ count }} times</button>
</template>

reactive: a reactive object

import { reactive } from 'vue'
const form = reactive({ name: '', email: '' })
form.name = 'Asha'

reactive makes an object deeply reactive and needs no .value. Do not replace the whole object (form = {...}) or destructure its properties into plain variables, because the link to Vue is lost. Many developers simply use ref for everything, which avoids these traps.

computed: values derived from other values

import { ref, computed } from 'vue'
const price = ref(250)
const qty = ref(3)
const total = computed(() => price.value * qty.value)

A computed value is cached and recalculated only when what it depends on changes. Use it for anything you can calculate from other state, such as totals, filtered lists and formatted text.

watch: run code when something changes

import { watch } from 'vue'
watch(qty, (newVal, oldVal) => {
  console.log(`Quantity changed from ${oldVal} to ${newVal}`)
})

Use watch for side effects such as saving to storage or calling an API. For calculating a value, prefer computed.

Lifecycle hooks

import { onMounted, onUnmounted } from 'vue'
onMounted(() => window.addEventListener('resize', onResize))
onUnmounted(() => window.removeEventListener('resize', onResize))

Reusing logic: composables

A composable is just a function that uses these tools and returns state. Move repeated logic, such as tracking the mouse or fetching data, into functions named useSomething(), and call them from any component.

// useCounter.js
import { ref } from 'vue'
export function useCounter(start = 0) {
  const count = ref(start)
  const increment = () => count.value++
  return { count, increment }
}

ref or reactive?

Both work, and the choice is partly style. ref works for primitives and objects alike and keeps the same pattern everywhere (.value in the script). reactive reads a little cleaner for grouped form data, but it cannot hold a primitive directly and loses reactivity if you destructure it. A safe approach is to use ref by default and reactive where an object genuinely feels natural. When you need to destructure a reactive object, use toRefs.

Props and emits with script setup

<script setup>
const props = defineProps({ title: String, count: { type: Number, default: 0 } })
const emit = defineEmits(['update'])

function save() {
  emit('update', props.count + 1)
}
</script>

Props flow down from parent to child and are read-only. A child tells its parent about changes by emitting events. For two-way binding on a component, Vue 3.4 and later offers defineModel.

Fetching data

<script setup>
import { ref, onMounted } from 'vue'
const posts = ref([])
const loading = ref(true)
const error = ref(null)

onMounted(async () => {
  try {
    const res = await fetch('/api/posts')
    posts.value = await res.json()
  } catch (e) {
    error.value = e
  } finally {
    loading.value = false
  }
})
</script>

Computed versus watch versus methods

  • Use computed to derive a value; it is cached.
  • Use a method when you need to run something on an event or pass arguments.
  • Use watch or watchEffect only for side effects, such as saving to storage, logging or calling an API.

Sharing state between components

For small apps, a composable that holds a ref outside the function can be shared by importing it in several components. For larger apps, use Pinia, the official state management library. It offers stores, devtools support and good TypeScript support.

// stores/cart.js
import { defineStore } from 'pinia'
export const useCartStore = defineStore('cart', {
  state: () => ({ items: [] }),
  getters: { count: (s) => s.items.length },
  actions: { add(item) { this.items.push(item) } },
})

Common beginner mistakes

  1. Forgetting .value in the script section.
  2. Mutating a prop inside the child instead of emitting an event.
  3. Using v-if and v-for together on the same element; filter the list with a computed value instead.
  4. Missing the key attribute in v-for lists.
  5. Doing heavy work inside the template instead of a computed property.
Tags:#vue#composition api#javascript
Found this helpful? Share it with friends & colleagues
Share:
insightforgeeks-editorial Verified Editorial Staff

Covering financial markets, commodity rates, and practical technology insights for India. Researched and fact-checked in accordance with our Editorial Policy.

Published on 16 November 2026General Information · Disclaimer

Recommended based on your reading interest

More in VueJS