Reactivity Core: The Composition API
9 min read
If you have ever built a web application where the user clicks a button, a number goes up, and the screen instantly reflects that new number without a page reload—you have witnessed reactivity.
In Vue.js, reactivity is the engine that keeps your data (JavaScript variables) and your view (HTML) perfectly in sync. Historically, Vue handled this using the Options API. But as applications grew larger and more complex, developers faced a wall. Enter the Composition API.
In this guide, we will break down the core of Vue's modern reactivity system. We will start from how to write a basic modern component, move to making data reactive, learn how to efficiently derive new data, and finally, how to trigger side-effects when data changes.
1. Introduction to the Composition API and <script setup> 🛠️
The Problem
Before the Composition API, Vue used the Options API. You declared your component's logic inside specific object properties: data(), methods, computed, and watch.
Imagine you are managing a large supermarket. In the Options API world, you are forced to group everything by its type. All the prices for every item (apples, mops, batteries) are kept in one giant ledger. All the instructions on how to order new items are kept in a separate giant binder. If an employee needs to understand everything about "Apples," they have to run back and forth between the price ledger, the ordering binder, and the inventory log.
In code, this meant that logic for a single feature (like a search bar) was scattered across hundreds of lines of code. You would scroll up and down like a confused squirrel trying to figure out how the search feature worked.
The Solution
The Composition API solves this by allowing you to group code by feature rather than by type. You can write all the variables, functions, and watchers related to the "Search" feature in one block, and everything related to "Pagination" in another.
To make writing the Composition API incredibly clean, Vue introduced the <script setup> block.
What is <script setup>?
<script setup> is a compile-time syntactic sugar for using the Composition API inside Single-File Components (SFCs).
When you use <script setup>, any variable or function declared inside it is automatically exposed to your HTML template. You do not need to explicitly return them.
<script setup>
import { ref } from 'vue'
// Logic for Feature A: Counter
const count = ref(0)
function increment() {
count.value++
}
// Logic for Feature B: Greeting
const message = 'Hello, Vue!'
</script>
<template>
<div>
<h1>{{ message }}</h1>
<button @click="increment">Count is: {{ count }}</button>
</div>
</template>Under the hood: When Vue compiles your .vue file, it takes the code inside <script setup> and wraps it inside the standard setup() function of the component. It automatically detects what variables the <template> needs and returns them.
Industry Standard: Today, almost no one writes new Vue 3 projects using the manual setup() function or the Options API. The <script setup> syntax is the undisputed industry standard due to its brevity and superior TypeScript inference.
2. Reactive Primitives: ref() vs reactive() ⚡
The Problem
Standard JavaScript variables are not reactive. If you declare let price = 10 and display it in your HTML, changing price = 20 in JavaScript will not update the screen. The browser has no idea the variable changed because JavaScript does not inherently broadcast variable mutations.
The Solution
Vue provides two main functions to create reactive state: ref() and reactive(). They tell Vue to track the variable and automatically update the DOM whenever the value changes.
Defining ref()
ref() is a function that takes an inner value and returns a reactive and mutable object with a single property called .value.
import { ref } from 'vue'
const age = ref(25)
// To access or mutate it in JavaScript, you MUST use .value
console.log(age.value) // 25
age.value = 26 Notice that in the <template>, you do not need to use .value. Vue automatically unwraps it for you:
<template>
<p>Your age is {{ age }}</p> <!-- Renders 26 -->
</template>Defining reactive()
reactive() is a function that takes a JavaScript object and returns a reactive proxy of that object.
import { reactive } from 'vue'
const user = reactive({
name: 'Alice',
age: 25
})
// No .value needed!
user.age = 26The Industry Standard: Which one to use?
You might look at reactive() and think, "Wow, no .value! I'll just use that everywhere!"
Stop right there. 🛑
While reactive() seems cleaner, it has a massive flaw: Destructuring breaks reactivity.
If you try to extract a property from a reactive object, it becomes a plain, disconnected variable:
const user = reactive({ name: 'Alice', age: 25 })
let { age } = user // ❌ Reactivity is LOST! 'age' is now just a plain number.Furthermore, reactive() cannot be used on primitive values like String, Number, or Boolean. It only works on objects.
Best Practice: The overwhelmingly common industry standard is to use ref() for absolutely everything, including objects and arrays. It provides a consistent mental model: if it's reactive, it has a .value in JavaScript.
// Industry standard approach
const user = ref({ name: 'Alice', age: 25 })
function haveBirthday() {
user.value.age++ // Safe, consistent, always works
}Under the hood: Vue 3 reactivity is powered by JavaScript Proxy objects. When you access .value, Vue's proxy records that your component "read" this data. When you change .value, the proxy triggers an alarm that tells Vue, "Hey! Update the components that read this data!"
3. Computed Properties: Efficient Derived State 🧮
The Problem
Sometimes you need state that depends on other state.
Imagine you are building a shopping cart. You have an array of items, each with a price. To get the total cost, you write a function calculateTotal() that loops through all items and adds them up.
If you use a standard function in your template like {{ calculateTotal() }}, Vue will run that heavy calculation loop every single time the component re-renders—even if the cart items haven't changed! If the user just typed their name in a form input, Vue re-renders, and your app recalculates the entire cart unnecessarily. Your app will become as slow as a tortoise moving through peanut butter.
The Solution
computed() is a function that takes a getter callback and returns a read-only reactive ref object. The returned value automatically tracks its reactive dependencies.
More importantly: Computed properties are cached.
<script setup>
import { ref, computed } from 'vue'
const items = ref([
{ name: 'Laptop', price: 1000 },
{ name: 'Mouse', price: 50 }
])
const discount = ref(10)
// This will only run when `items` or `discount` changes
const finalPrice = computed(() => {
console.log('Calculating total...') // Proof it doesn't run unnecessarily
const total = items.value.reduce((sum, item) => sum + item.price, 0)
return total - discount.value
})
</script>
<template>
<div>
<p>Total: ${{ finalPrice }}</p>
<p>Total again: ${{ finalPrice }}</p> <!-- Uses the cached result! -->
</div>
</template>How it works practically
Think of a computed property like asking a cashier for the total bill.
- The cashier calculates the total ($1050) and writes it down on a piece of paper (the Cache).
- If you ask for the total again five seconds later, the cashier doesn't scan all the items again. They just read the number from the paper.
- If you add a new item to the cart (a dependency changes), the cashier throws away the paper and calculates a new total.
Industry Practice: Use computed for any data derivation. Filtering a list? Use computed. Checking if a form is valid? Use computed. Never put complex logic directly into your HTML template.
4. Watchers: Reacting to State Changes 👁️
The Problem
Computed properties are great for calculating new data, but what if you need to do something when data changes?
What if you need to make an API call to your backend every time the user types in a search box? Or save the user's progress to localStorage every time their score changes? Computed properties cannot be used for this because they must be pure functions (they should return a value, not cause side effects).
The Solution
watch() is a function that observes one or more reactive data sources and invokes a callback function when the sources change.
<script setup>
import { ref, watch } from 'vue'
const searchQuery = ref('')
const searchResults = ref([])
const isSearching = ref(false)
// Watch the searchQuery variable
watch(searchQuery, async (newValue, oldValue) => {
if (newValue === '') {
searchResults.value = []
return
}
isSearching.value = true
// Simulate an API Call
try {
const response = await fetch(`https://api.example.com/search?q=${newValue}`)
searchResults.value = await response.json()
} catch (error) {
console.error("Search failed")
} finally {
isSearching.value = false
}
})
</script>
<template>
<input v-model="searchQuery" placeholder="Search users..." />
<span v-if="isSearching">Loading...</span>
</template>Deep Watching
By default, watch is shallow. If you watch an array or object, it only triggers if the entire array/object is replaced. If you mutate a nested property (like changing an item inside an array), the watcher won't notice unless you tell it to look deeper.
const user = ref({ name: 'John', preferences: { darkTheme: false } })
// The { deep: true } option forces the watcher to traverse all nested properties
watch(user, (newValue) => {
console.log('User changed!', newValue)
}, { deep: true })Note: Deep watching can be computationally expensive if the object is huge, so use it only when necessary.
watchEffect vs watch (Briefly)
You will often see watchEffect() in the industry.
watchrequires you to explicitly state what you are watching. It also gives you access to theoldValue.watchEffectautomatically runs immediately, figures out which reactive variables you used inside it, and watches them automatically.
Industry Practice: Use watch when you need exact control over what triggers the side effect, or if you need to know the previous value before the change. Use watchEffect for simpler automatic syncing (like automatically saving a configuration object to a database whenever any part of it changes).
📚 References & Further Reading
To dive even deeper into these topics, keep the official documentation handy. Vue's documentation is widely considered one of the best in the open-source world.
- Vue.js Official Documentation: Reactivity Fundamentals
- Vue.js Official Documentation: `<script setup>`
- Vue.js Official Documentation: Computed Properties
- Vue.js Official Documentation: Watchers
- Installation / Getting Started with Vue (Always check here for the latest
npm create vue@latestcommands)
Challenge
Challenge: Build a Reactive Shopping Cart Summary
You are tasked with creating the logic for a shopping cart summary component using Vue's Composition API. All logic must be contained within the <script setup> block.
Requirements:
State Management (
ref):- The
cartItemsstate is already provided. Do not modify its initial structure. - Create a
refnamedshippingCostand initialize it with a value of15. - Create a
refnameddiscountCodeand initialize it as an empty string ('').
- The
Derived State (
computed):- Create a
computedproperty namedsubtotal. It must calculate the total cost of all items in the cart (price * quantity). - Create a
computedproperty namedgrandTotal. This should calculate the final price by adding thesubtotalandshippingCost. If thediscountCode's value is exactly'SALE20', a 20% discount should be applied to thesubtotalbefore adding the shipping cost.
- Create a
Side Effects (
watch):- Create a
watcher that observes thesubtotal. If the subtotal exceeds100, it should set theshippingCostto0. Otherwise, theshippingCostshould be15. - Create a second
watcher that monitors thecartItemsarray for any changes to the properties of the objects within it (e.g., a change inquantity). For this challenge, the watcher's callback function can be empty, but it must be configured to perform a deep watch.
- Create a
Expected result
Your final code should correctly implement all the required reactive logic within the <script setup> block.
Refs: The
shippingCostanddiscountCodevariables must be created usingref()with their specified initial values.Computed Properties:
- The
subtotalcomputed property should accesscartItems.valueand use a method likereduce()to iterate through the items, returning the sum ofitem.price * item.quantityfor all items. - The
grandTotalcomputed property should read the values fromsubtotal.value,shippingCost.value, anddiscountCode.value. It must contain conditional logic to check if the discount code is'SALE20'and apply a* 0.8calculation to the subtotal if it matches.
- The
Watchers:
- A
watchfunction should be configured withsubtotalas its source. The callback function will receive the new subtotal value as an argument and use anif/elsestatement to setshippingCost.valueto either0or15based on the condition. - A second
watchfunction must be configured withcartItemsas its source and include an options object{ deep: true }as its third argument. The callback function can be a simple empty arrow function() => {}.
- A