Vue reactivity and state: ref, computed, Pinia
Vue’s reactivity system is what makes templates update by themselves: when a component renders, Vue records which reactive values it read, and when one of them changes, Vue re-runs exactly the effects that depend on it. Understanding when to derive a value and when to react to a change is the core skill in writing maintainable Vue code. This page covers reactive state with ref and reactive, derived state with computed, side effects with watchers, reusable logic in composables, and application-wide state with Pinia. The examples follow an OrdersPortal cart and order board.
The samples target Vue 3.5 and Pinia 4.1. Plain .mjs files run directly with Node.js 22 (node cart.mjs), because the reactivity APIs work outside components; component samples were compiled with @vue/compiler-sfc, mounted into a jsdom document by the main.js driver shown with them, and the printed output is shown below each.
Topics on this page
Section titled “Topics on this page”| Topic | Use it when |
|---|---|
| Ref and reactive | You declare state that the UI should follow. |
| Computed values | A value can be calculated from other state. |
| Watchers | A change must trigger a side effect such as a request or a save. |
| Composables | Several components need the same stateful logic. |
| Shared state with Pinia | Distant components and pages share data and actions. |
Ref and reactive
Section titled “Ref and reactive”ref(value) wraps any value, primitive or object, in an object with a .value property; reading .value registers a dependency and writing it triggers updates. Objects stored in a ref are made deeply reactive. reactive(object) returns a deeply reactive proxy of an object, read and written like a plain object without .value. The Vue docs recommend ref as the default because it works for every type and can be reassigned and passed around without losing reactivity; templates unwrap top-level refs, so you only write .value in script.
The main limitation of reactive is that the reactivity lives on the proxy: destructuring it or assigning a new object to the variable disconnects you from it. toRefs converts each property into a ref linked to the original, which is how composables and stores return state that callers can destructure.
// cart.mjs - Vue's reactivity system works outside components too: node cart.mjsimport { ref, reactive, computed, isRef, toRefs } from 'vue'
const discountPercent = ref(0) // a primitive: use ref, read .valueconst cart = reactive({ // an object: reactive proxy, no .value customer: 'ada@example.test', lines: [{ sku: 'SKU-RED-01', unitPrice: 19.99, quantity: 2 }],})
let subtotalRuns = 0const subtotal = computed(() => { subtotalRuns++ return cart.lines.reduce((sum, l) => sum + l.unitPrice * l.quantity, 0)})const total = computed(() => +(subtotal.value * (1 - discountPercent.value / 100)).toFixed(2))
console.log(total.value, total.value, `subtotal runs: ${subtotalRuns}`) // cached: computed once
cart.lines.push({ sku: 'SKU-BLU-07', unitPrice: 5.5, quantity: 4 }) // deep reactivitydiscountPercent.value = 10console.log(total.value, `subtotal runs: ${subtotalRuns}`)
const { customer } = cart // destructuring loses reactivityconst refs = toRefs(cart) // ...toRefs keeps itcart.customer = 'ben@example.test'console.log(customer, refs.customer.value, isRef(refs.customer))Output:
39.98 39.98 subtotal runs: 155.78 subtotal runs: 2ada@example.test ben@example.test truePitfalls:
- Destructuring reactive objects (
const { customer } = cart) copies the current value; usetoRefsor read through the object. - Replacing a
reactiveobject (cart = reactive({...})) leaves components bound to the old proxy; mutate it, or use arefand assign.value. - Forgetting
.valuein script.if (discountPercent > 0)compares the ref object, not its value; TypeScript and the Vue language tools catch this.
Computed values
Section titled “Computed values”computed(getter) creates a read-only ref whose value is calculated from other reactive state. It is cached: the getter runs again only when one of the values it read has changed, so reading total.value twice in the sample above ran the subtotal calculation once. That makes computed properties the right tool for anything derived: totals, filtered and sorted lists, validity flags, labels.
Keep getters pure and fast: no requests, no DOM changes, no mutation of other state. A computed with a setter (computed({ get, set })) exists for adapters such as mapping a store value to a form field, but most derived values should be read-only. Since Vue 3.4, a computed only triggers its dependents when its new value is actually different, which avoids needless re-renders when an input changes but the result does not.
The cart.mjs sample above shows both subtotal and total as computed values, with total depending on subtotal and on the discount ref.
Pitfalls:
- Side effects in a getter. A computed that saves or fetches runs at unpredictable times; use a watcher.
- Mutating the computed result. Sorting
visible.valuein place changes the source array; return new arrays from getters and treat results as read-only. - Methods instead of computed for expensive work. A method called in the template runs on every render; a computed is cached.
Watchers
Section titled “Watchers”Watchers run side effects when state changes. watch(source, callback) watches an explicit source, such as a ref, a getter function (() => props.orderId) or an array of sources, and calls the callback with the new and old values; options include immediate, deep and once. watchEffect(fn) runs a function immediately and re-runs it whenever anything it read changes, without listing sources. Watchers created in <script setup> stop automatically when the component unmounts; outside a component, call the stop function they return.
Async work in watchers needs cancellation: if the user types again before a search returns, the old request must not overwrite the new results. Vue 3.5 adds onWatcherCleanup(), which registers a callback that runs before the watcher fires again or when it stops. Older versions pass an onCleanup function as the third callback argument for the same purpose.
// search-watch.mjs - node search-watch.mjsimport { ref, watch, watchEffect, onWatcherCleanup } from 'vue'
// Fake API: answers after 30 ms unless aborted.function searchOrders(query, signal) { return new Promise((resolve, reject) => { const timer = setTimeout(() => resolve([`order matching "${query}"`]), 30) signal.addEventListener('abort', () => { clearTimeout(timer); reject(new DOMException('Aborted', 'AbortError')) }) })}
const query = ref('')const results = ref([])const log = (msg) => console.log(msg)
watch(query, async (q) => { if (q.length < 3) { results.value = []; return } const controller = new AbortController() onWatcherCleanup(() => { // Vue 3.5+: runs before the next callback or on stop controller.abort() log(`cancelled search for "${q}"`) }) try { results.value = await searchOrders(q, controller.signal) } catch (error) { if (error.name !== 'AbortError') throw error }})
const stopLogging = watchEffect(() => log(`results: ${JSON.stringify(results.value)}`)) // runs now, then on change
query.value = 'ada'await new Promise((r) => setTimeout(r, 10))query.value = 'ada lo' // arrives before the first search finishesawait new Promise((r) => setTimeout(r, 50))stopLogging()Output:
results: []cancelled search for "ada"results: ["order matching \"ada lo\""]Pitfalls:
- Watching to derive state.
watch(lines, () => { total.value = ... })should be a computed property. - Watching a reactive property directly.
watch(cart.customer, ...)passes a string, not a source; use a getter:watch(() => cart.customer, ...). - Deep watchers on large objects traverse every nested property on each change; watch the specific getter you need.
Composables
Section titled “Composables”A composable is a function, by convention named use..., that uses Vue’s Composition API to encapsulate and reuse stateful logic, the Vue counterpart of a React custom hook. Each call creates fresh state, so two components using useOrderFilter filter independently. Composables return plain objects of refs (not a reactive object) so callers can destructure them, and accept inputs as refs, getters or plain values, normalized with toValue() (Vue 3.3 and later) so they react to changes whatever the caller passes.
The Vue ecosystem library VueUse collects hundreds of tested composables (useDebounceFn, useLocalStorage, useMediaQuery); check it before writing your own.
// useOrderFilter.js - a composable: reusable stateful logic built from refs and computedimport { computed, ref, toValue } from 'vue'
export function useOrderFilter(orders) { // orders: an array, a ref or a getter const status = ref('all') const search = ref('')
const visible = computed(() => toValue(orders).filter((o) => (status.value === 'all' || o.status === status.value) && o.customer.toLowerCase().includes(search.value.trim().toLowerCase())))
const counts = computed(() => { const result = { all: toValue(orders).length } for (const o of toValue(orders)) result[o.status] = (result[o.status] ?? 0) + 1 return result })
return { status, search, visible, counts }}<script setup>import { ref } from 'vue'import { useOrderFilter } from './useOrderFilter.js'
const orders = ref([ { id: 1001, customer: 'Ada Lopez', status: 'open' }, { id: 1002, customer: 'Ben Ortiz', status: 'shipped' }, { id: 1003, customer: 'Ada Lopez', status: 'shipped' },])const { status, search, visible, counts } = useOrderFilter(orders)</script>
<template> <select v-model="status" aria-label="Status"> <option v-for="(n, s) in counts" :key="s" :value="s">{{ s }} ({{ n }})</option> </select> <input v-model="search" aria-label="Customer" /> <ul><li v-for="o in visible" :key="o.id">{{ o.id }} {{ o.customer }}</li></ul></template>// main.js - mounts OrderBoard in a jsdom document, then filters by status and customer.import { createApp, nextTick } from 'vue'import OrderBoard from './OrderBoard.vue'
createApp(OrderBoard).mount('#app')const show = () => console.log([...document.querySelectorAll('li')].map((li) => li.textContent).join(', ') || '(none)')const set = async (selector, value, event) => { const el = document.querySelector(selector); el.value = value; el.dispatchEvent(new Event(event)); await nextTick()}show()await set('select', 'shipped', 'change'); show()await set('input', 'ada', 'input'); show()console.log(document.querySelector('select').textContent)Output:
1001 Ada Lopez, 1002 Ben Ortiz, 1003 Ada Lopez1002 Ben Ortiz, 1003 Ada Lopez1003 Ada Lopezall (3)open (1)shipped (2)Pitfalls:
- Calling composables conditionally or asynchronously. Call them synchronously in
<script setup>so lifecycle hooks and watchers attach to the component. - Expecting shared state. State created inside the function is per call; for shared state, create it outside the function (a module-level singleton) or use a store.
- Returning a
reactive()object forces callers to keep the object intact; return refs.
Shared state with Pinia
Section titled “Shared state with Pinia”Pinia is Vue’s official state management library. A store, created with defineStore(id, setup), holds state shared by any component that calls useCartStore(), with one instance per app. In the setup store form, refs become state, computeds become getters and functions become actions, exactly like a composable. Stores work with Vue DevTools (time travel, state inspection), support plugins such as persistence, render correctly in server-side rendering, and are easy to test by creating a fresh Pinia per test.
Pinia 4 (July 2026) is ESM-only and expects @vue/devtools-api to be installed alongside it; the store API is unchanged from Pinia 3. Use storeToRefs(store) to destructure state and getters without losing reactivity; actions can be destructured directly. For server data such as order lists, pair stores with a data-fetching layer (for example Pinia Colada or TanStack Query for Vue) rather than hand-writing caching.
// cartStore.js - a setup store: refs are state, computed are getters, functions are actionsimport { defineStore } from 'pinia'import { computed, ref } from 'vue'
export const useCartStore = defineStore('cart', () => { const lines = ref([]) const couponCode = ref(null)
const itemCount = computed(() => lines.value.reduce((n, l) => n + l.quantity, 0)) const total = computed(() => { const subtotal = lines.value.reduce((sum, l) => sum + l.unitPrice * l.quantity, 0) return +(couponCode.value === 'SAVE-10' ? subtotal * 0.9 : subtotal).toFixed(2) })
function add(product, quantity = 1) { const existing = lines.value.find((l) => l.sku === product.sku) if (existing) existing.quantity += quantity else lines.value.push({ ...product, quantity }) }
async function applyCoupon(code, validate) { if (!(await validate(code))) throw new Error(`Coupon ${code} is not valid`) couponCode.value = code }
return { lines, couponCode, itemCount, total, add, applyCoupon }})// store-demo.mjs - uses the store outside a component, as a unit test would: node store-demo.mjsimport { createPinia, setActivePinia, storeToRefs } from 'pinia'import { useCartStore } from './cartStore.js'
setActivePinia(createPinia()) // in an app: app.use(createPinia())const cart = useCartStore()const { itemCount, total } = storeToRefs(cart) // destructure state and getters without losing reactivity
cart.add({ sku: 'SKU-RED-01', unitPrice: 19.99 }, 2)cart.add({ sku: 'SKU-BLU-07', unitPrice: 5.5 }, 4)cart.add({ sku: 'SKU-RED-01', unitPrice: 19.99 })console.log(`${itemCount.value} items, ${total.value} EUR`)
const validate = async (code) => code === 'SAVE-10'await cart.applyCoupon('SAVE-10', validate)console.log(`with coupon: ${total.value} EUR`)await cart.applyCoupon('FREE-99', validate).catch((e) => console.log(e.message))console.log(useCartStore() === cart) // one instance per PiniaOutput:
7 items, 81.97 EURwith coupon: 73.77 EURCoupon FREE-99 is not validtruePitfalls:
- Destructuring a store (
const { total } = useCartStore()) gives a snapshot; usestoreToRefs. - Everything in a store. Form input, open dialogs and per-screen filters belong in components or composables; stores are for state shared across screens.
- Module-level singletons with server rendering. A plain module-level
refis shared between all users’ requests on the server; Pinia creates state per app instance and avoids that leak.
Choosing between them
Section titled “Choosing between them”| Situation | Use |
|---|---|
| Local state of one component | ref in <script setup> |
| Value calculated from other state | computed |
| Request, save, log or DOM work after a change | watch or watchEffect with cleanup |
| Same logic in several components, separate state | Composable |
| Data passed down a deep subtree only | provide and inject |
| Data and actions shared across pages | Pinia store |
Interview questions
Section titled “Interview questions”When do you use ref and when reactive?
Use ref by default: it works for every type, can be reassigned and survives being passed around. reactive suits a cohesive object you always access through the object itself; destructuring or replacing it loses reactivity.
What is the difference between computed and watch?
computed derives a cached value from other state and must be pure. watch performs a side effect in response to a change, such as a request or a write to storage. If you find yourself setting state inside a watcher from other state, it should usually be a computed.
How does Vue know which components to re-render? Reactive reads inside a component’s render effect are tracked as dependencies through proxies and ref getters. When a tracked value changes, Vue schedules only the effects that depend on it, batching updates until the next tick.
How do you cancel stale async work in a watcher?
Create an AbortController per run and abort it in onWatcherCleanup (Vue 3.5 and later) or the onCleanup callback argument, which Vue calls before the next run and when the watcher stops.
Senior scenario: a large Vue app has a single “global” store with 3,000 lines and every page imports it. How do you restructure it? Split by domain into small stores (cart, session, catalog), each owning its state and actions, with stores calling each other where needed. Move server data out of stores into a data-fetching layer with caching, and move page-local state into components or composables. Migrate behind the same public getters and actions so pages change gradually, and add store unit tests with a fresh Pinia per test before refactoring.
Related pages
Section titled “Related pages”- Vue overview for versions and the reading path.
- Components and templates for props, emits,
v-modeland slots. - React hooks, effects and context for the React equivalents of watchers, composables and shared state.