State in Vue
Put each piece of state in the smallest place that works, from a local ref up to a Pinia store, the URL or a server-data cache. A composable creates new state on each call, but state at module level is shared by everyone, and on a server it can leak between users. Use storeToRefs when you destructure a store, shallowRef for big data, and cancel old requests so a stale answer never wins.
Author: bezzad
Contents
The problem: two forms that type together
Our online shop has a checkout page with two address forms: shipping and billing. Both use the same composable:
// useAddressForm.ts
import { ref } from 'vue'
const street = ref('') // module level: one copy for the whole app
export function useAddressForm() {
return { street }
}
- The user types a street in the shipping form.
- The same text appears in the billing form too.
- Later the shop moves to server rendering. One user sometimes sees part of the address of another user.
Vue did not fail here. The state lived in the wrong place. Most state bugs in Vue apps come from one question: where does this state live, and who shares it?
Where state lives
Choose the smallest place that works. Move state to a wider place only when you have a real reason.
- A local ref: only one component needs it. The search box text, an “is open” flag.
- Props and emits: a parent and its child share it. The parent owns it.
- Provide and inject: many components deep inside one part of the page need it, like the currency for all prices in a product list.
- A Pinia store: far apart parts of the app need it, like the cart. The header badge and the checkout page both read it.
- The URL: the user should be able to share it, bookmark it, or come back to it with the back button. Search text, filters, sort order, page number.
- Server data: it really lives on the server. In the browser you only keep a copy. You need loading and error states, and you must decide when the copy is old.
Provide and inject
Provide and inject skip the props chain. A layout provides a value, and any component below it can inject it:
// currency-key.ts
import type { InjectionKey, Ref } from 'vue'
export type Currency = 'USD' | 'EUR'
export const currencyKey: InjectionKey<Ref<Currency>> = Symbol('currency')
<script setup lang="ts">
import { provide, ref } from 'vue'
import { currencyKey, type Currency } from './currency-key'
const currency = ref<Currency>('USD')
provide(currencyKey, currency) // provide the ref, not its value
</script>
<template>
<slot />
</template>
<script setup lang="ts">
import { inject } from 'vue'
import { currencyKey } from './currency-key'
defineProps<{ amount: number }>()
const currency = inject(currencyKey)
</script>
<template>
<span>{{ amount }} {{ currency }}</span>
</template>
- Provide the ref itself. If you provide currency.value, the children get a plain string and never see changes.
- The InjectionKey type gives you type checking for the injected value.
- Keep it for one part of the page. For state the whole app shares, a store is easier to find and debug.
Composables
A composable is a function whose name starts with use. It uses the Composition API inside and returns state and functions. It is how Vue shares logic.
// useAddressForm.ts
import { computed, ref } from 'vue'
export function useAddressForm() {
const street = ref('') // a new ref for each call
const city = ref('')
const isValid = computed(() => street.value.trim() !== '' && city.value.trim() !== '')
return { street, city, isValid }
}
- State created inside the function is new on each call. The shipping form and the billing form each call useAddressForm and each get their own street.
- State declared at module level is created once, when the file is first imported. Every component that calls the composable gets the same object.
- In the browser, “everyone” is one tab. Sometimes you want shared state. Then say so clearly, and usually use a Pinia store.
- On a server (SSR), “everyone” is every user. The server process imports the module once and then renders pages for many users. Module-level state can carry the data of one user into the page of another.
- Return refs, not one reactive object. Then the caller can destructure the result safely.
- Call a composable synchronously in script setup, not later inside a timer or an event handler. Its watchers and lifecycle hooks belong to the component that is running setup.
Pinia setup stores
Pinia is the official store library for Vue. A setup store looks like a composable:
// stores/cart.ts
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
export type CartItem = { id: number; name: string; price: number; qty: number }
export const useCartStore = defineStore('cart', () => {
const items = ref<CartItem[]>([])
const total = computed(() =>
items.value.reduce((sum, item) => sum + item.price * item.qty, 0),
)
function add(product: Omit<CartItem, 'qty'>) {
const existing = items.value.find((item) => item.id === product.id)
if (existing) existing.qty++
else items.value.push({ ...product, qty: 1 })
}
function remove(id: number) {
items.value = items.value.filter((item) => item.id !== id)
}
return { items, total, add, remove }
})
- Each ref becomes state. Each computed becomes a getter. Each function becomes an action.
- Return all the state. Pinia needs every state ref in the returned object, for example for devtools and server rendering.
- Change state in actions. The add action holds the rule “same product means a bigger quantity”. Components only call it.
- The store is created once per Pinia instance. In the browser that is once per app. With SSR you create a new Pinia for each request, so users do not share a cart.
Destructuring a store
The store object is reactive. Destructuring it copies plain values, like with any reactive object. Use storeToRefs:
<script setup lang="ts">
import { storeToRefs } from 'pinia'
import { useCartStore } from '../stores/cart'
const cart = useCartStore()
const { items, total } = storeToRefs(cart) // refs: stay reactive
const { remove } = cart // actions are plain functions
</script>
<template>
<ul>
<li v-for="item in items" :key="item.id">
{{ item.name }} x {{ item.qty }}
<button type="button" @click="remove(item.id)">Remove</button>
</li>
</ul>
<p>Total: {{ total }}</p>
</template>
- The storeToRefs function returns refs for the state and the getters. It skips actions.
- Actions can be destructured directly from the store. They are bound to the store.
- You can also skip destructuring and write cart.total in the template. That is always safe.
Big data: shallowRef and markRaw
The admin page of the shop shows 50,000 inventory rows. A normal ref makes the whole array deeply reactive.
- A deep ref wraps each row in a Proxy when the row is read.
- Each property read is tracked. Sorting or filtering 50,000 rows means a huge number of tracked reads and a lot of extra memory.
- We never change one field of one row in place. We load the list, show it, and replace it.
import { shallowRef } from 'vue'
type Row = { id: number; sku: string; price: number; stock: number }
const rows = shallowRef<Row[]>([])
async function load() {
const res = await fetch('/api/admin/inventory')
rows.value = await res.json() // only .value is tracked
}
function updatePrice(id: number, price: number) {
// replace, do not mutate: a shallowRef does not see nested changes
rows.value = rows.value.map((row) => (row.id === id ? { ...row, price } : row))
}
- A shallowRef only tracks its value property. The rows stay plain objects.
- You must replace the value to update the screen. If you change a nested field in place, nothing updates. The triggerRef function can force an update, but replacing is clearer.
- The markRaw function marks one object as never reactive. Use it for objects Vue should not wrap at all, like an instance of a chart or map library that you put inside reactive state.
- Do not render 50,000 rows either. Use pagination or a virtual list. Less reactivity does not fix a huge DOM.
Server data in a composable
Server data needs three states: loading, error and data. It also needs one more thing that people forget: an old answer must never overwrite a new one.
// useFetchJson.ts
import { onWatcherCleanup, ref, shallowRef, toValue, watchEffect } from 'vue'
import type { MaybeRefOrGetter } from 'vue'
export function useFetchJson<T>(url: MaybeRefOrGetter<string>) {
const data = shallowRef<T | null>(null)
const error = shallowRef<Error | null>(null)
const loading = ref(false)
watchEffect(async () => {
const controller = new AbortController()
onWatcherCleanup(() => controller.abort()) // cancel the old request
const currentUrl = toValue(url) // read before await, so it is tracked
loading.value = true
error.value = null
try {
const res = await fetch(currentUrl, { signal: controller.signal })
if (!res.ok) throw new Error(`HTTP ${res.status}`)
data.value = await res.json()
} catch (e) {
if (controller.signal.aborted) return // a newer request is running
error.value = e instanceof Error ? e : new Error(String(e))
}
loading.value = false
})
return { data, error, loading }
}
<script setup lang="ts">
import { useFetchJson } from '../composables/useFetchJson'
type Product = { id: number; name: string; price: number }
const { productId } = defineProps<{ productId: number }>()
const { data: product, error, loading } = useFetchJson<Product>(
() => `/api/products/${productId}`,
)
</script>
<template>
<p v-if="loading">Loading</p>
<p v-else-if="error">Could not load the product.</p>
<h1 v-else-if="product">{{ product.name }}</h1>
</template>
- The URL is a getter. The watchEffect reads it, so a new product id starts a new request.
- Read every reactive source before the first await. After an await, Vue does not track reads any more.
- Before each new run, Vue calls the cleanup. The old request is aborted. Its error is ignored, and loading stays true for the new request.
- Without the cleanup, the slower answer wins. The user clicks product 1 and then product 2. If the answer for product 1 is slow, it arrives last and the page shows product 1 under the URL of product 2.
This small composable has no cache and no retry. Real apps often use a library for server data, like TanStack Query for Vue. It adds caching, refetching and request deduplication. The ideas stay the same.
The URL as state
The user sets the category to “shoes” and sends the link to a friend. The friend must see the same list. So the filter belongs in the URL query, not in a ref:
import { computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
const route = useRoute()
const router = useRouter()
const category = computed({
get: () => (typeof route.query.category === 'string' ? route.query.category : 'all'),
set: (value: string) => {
router.replace({
query: { ...route.query, category: value === 'all' ? undefined : value },
})
},
})
- The URL is the single source. The computed reads from it and writes to it. You can use it with v-model on a select tag.
- Use replace for filters that change often, like typing in the search box. A push adds a history entry for every change, and the back button becomes useless.
- Query values are strings, and the user can edit them. Always parse and check them, with a safe default.
- Use this value as the input of server data. For example, pass a getter that builds the API URL from category.value to useFetchJson.
Common mistakes
| Mistake | Result | Better way |
|---|---|---|
| Composable state at module level by accident | Two forms share data. With SSR, users can see each other’s data. | Create state inside the function. Use a store for real shared state. |
| Destructuring a Pinia store directly | State and getters lose reactivity. | Use storeToRefs. Actions can be destructured directly. |
| Everything in the store | A big global object. Hard to know who changes what. | Keep state local until it really needs to be shared. |
| A deep ref for 50,000 read-only rows | Slow sorting and filtering, extra memory. | Use shallowRef and replace the array. |
| Fetching in a watcher with no cancel | A stale answer shows the wrong product. | Abort the old request with onWatcherCleanup. |
| Filters only in a ref | Refresh, the back button and shared links lose the filter. | Keep filters in the URL query. |
| Providing ref.value instead of the ref | Children never see changes. | Provide the ref itself. |
Summary in seven lines
- Keep each piece of state in the smallest place that works: local ref, props, provide and inject, store, URL, server cache.
- A composable shares logic. State inside the function is per call. State at module level is shared by everyone.
- On a server, module-level state is shared by all users. Create a new app and a new Pinia for each request.
- A Pinia setup store is refs, computeds and functions. Change state in actions.
- Destructure a store with storeToRefs. Actions can be taken directly.
- For big data you only replace, use shallowRef. Use markRaw for objects Vue should never wrap.
- Server data needs loading, error and cancel. Filters that users share belong in the URL.