Pinia setup stores and plugins
Write Pinia stores with the Composition API, use composables and watchers inside them, compose stores, and extend every store with a plugin.
Pinia setup stores and plugins
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- A setup store passes defineStore a function instead of an object: refs become state, computeds become getters, and functions become actions.
- Every piece of state must be returned from a setup store; unreturned or readonly state breaks devtools, SSR hydration, and plugins.
- Setup stores can use watchers, any composable, and inject() for app-level provides such as the router, which option stores cannot do cleanly.
- $reset() exists only on option stores; a setup store that needs a reset defines its own action for it.
- One store uses another by calling its useXStore() function inside a getter, action, or the setup function body, never at module top level.
- A Pinia plugin is a function registered with pinia.use() that runs once for each store, and can add properties, subscribe to changes, wrap actions, or read custom options passed to defineStore.
The same store, written as a composable
The option store from the last lesson mirrors the Options API. Most Vue code is now written with the Composition API, and Pinia supports that style too. Pass defineStore a function instead of an object, and write the body exactly like <script setup>:
// stores/cart.js
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
export const useCartStore = defineStore('cart', () => {
const items = ref([])
const couponCode = ref(null)
const itemCount = computed(() => items.value.reduce((n, i) => n + i.qty, 0))
const subtotal = computed(() =>
items.value.reduce((sum, i) => sum + i.price * i.qty, 0),
)
function add(product) {
const line = items.value.find((i) => i.id === product.id)
if (line) line.qty++
else items.value.push({ ...product, qty: 1 })
}
function $reset() {
items.value = []
couponCode.value = null
}
return { items, couponCode, itemCount, subtotal, add, $reset }
})
The mapping is mechanical: ref() and reactive() become state, computed() becomes a getter, and a plain function becomes an action. Components use the store the same way whichever syntax defined it: useCartStore(), storeToRefs for state and getters, actions destructured directly.
Two rules come with this freedom.
Return all state. Pinia decides what counts as state by looking at what you return. A ref you keep private is invisible to Vue Devtools, isn’t serialized for SSR hydration, and can’t be seen by plugins. Pinia’s docs are explicit that unreturned or readonly state breaks those features. If something truly needs to be private, it probably belongs in a composable rather than a store.
There is no automatic $reset(). An option store can rebuild its state by calling state() again. A setup store has no such function to call, so if you need a reset, write one, as above.
Why bother: what setup stores can do
Setup stores are more than a syntax preference. Because the body is an ordinary Composition API function, you can use things an option store can’t express cleanly.
Watchers inside the store.
watch(items, (value) => localStorage.setItem('cart', JSON.stringify(value)), {
deep: true,
})
Any composable. A VueUse composable or one of your own can provide state directly:
import { useLocalStorage } from '@vueuse/core'
export const useSettingsStore = defineStore('settings', () => {
const theme = useLocalStorage('theme', 'light')
return { theme }
})
App-level provides via inject(). Anything provided with app.provide() can be injected in a setup store, and composables like Vue Router’s useRoute() work too:
import { useRoute } from 'vue-router'
export const useSearchStore = defineStore('search', () => {
const route = useRoute()
const query = computed(() => route.query.q ?? '')
return { query }
})
Pinia’s docs add a caveat worth repeating: composables that hold their own state get more complicated under server-side rendering, because that state has to be serialized and hydrated correctly. That is the territory of the SSR and hydration lesson.
One store using another
Stores often depend on each other. The checkout store needs the cart and the signed-in user. You call the other store’s use function inside your store, not at the top of the module:
import { useAuthStore } from './auth'
import { useCartStore } from './cart'
export const useCheckoutStore = defineStore('checkout', () => {
const auth = useAuthStore()
const cart = useCartStore()
async function placeOrder() {
if (!auth.user) throw new Error('Not signed in')
await fetch('/api/orders', {
method: 'POST',
body: JSON.stringify({ userId: auth.user.id, items: cart.items }),
})
cart.$reset()
}
return { placeOrder }
})
The placement matters. Code at module top level runs when the file is first imported, which may be before app.use(pinia). Inside the setup function, or inside an option store’s getter or action, you’re guaranteed an active Pinia. Avoid two setup stores that each read the other’s state directly in their setup body; that is a cycle neither can finish.
Plugins: one function, every store
A Pinia plugin is a function that Pinia calls once for each store as it’s created. It receives a context object with store, app, pinia, and options (the definition passed to defineStore), and anything it returns is merged into the store.
Think of it like a building’s electrical code: you don’t wire each office separately, you set the rule once and every new room is built to it.
// plugins/piniaPersist.js
export function persistPlugin({ store, options }) {
if (!options.persist) return
const key = `pinia:${store.$id}`
const saved = localStorage.getItem(key)
if (saved) store.$patch(JSON.parse(saved))
store.$subscribe((_mutation, state) => {
localStorage.setItem(key, JSON.stringify(state))
})
}
// main.js
const pinia = createPinia()
pinia.use(persistPlugin)
app.use(pinia)
The persist flag is a custom option: Pinia lets you put extra keys in a store definition for plugins to read. For a setup store, custom options go in a third argument:
export const useCartStore = defineStore('cart', () => { /* ... */ }, {
persist: true,
})
Plugins can also wrap every action with store.$onAction() (for logging or error reporting), or add shared properties such as an API client. One ordering rule catches people out: a plugin only applies to stores created after it was registered and after Pinia was installed on the app.
You rarely need to write a persistence plugin yourself. Community plugins such as pinia-plugin-persistedstate do it with options for storage, key names, and which fields to keep. Writing the small version once is still the fastest way to understand what those plugins are doing.
What the video covers
Alexander Lichter’s video is a recent, practical case for setup stores. He migrates an option store to a setup store, explains why, uses composables inside a store, and shows how to keep store code organised as it grows. His Nuxt section (from about 8:24) belongs to the Nuxt group of this roadmap and can be skipped for now. The video doesn’t cover plugins at all. The plugin section above carries that part, and LearnVue’s persistence video in the links below shows the same idea built by hand and with community plugins.
Where this fits
Next is Vuex and migrating to Pinia, for readers who meet an older store in an existing codebase. TypeScript typing for stores is covered in TypeScript with Vue.
Check yourself
A setup store declares const draft = ref('') but only returns { save }. What goes wrong?
Pinia only treats returned refs as state. draft becomes hidden local state: it won't appear in Vue Devtools, it won't be serialized and hydrated under SSR, and plugins such as a persistence plugin can't see it. Return every ref the store holds.
Why does calling useAuthStore() at the top level of stores/cart.js, outside defineStore, fail, while calling it inside an action works?
At module top level there may be no active Pinia instance yet, because the module is evaluated when it's first imported, possibly before app.use(pinia) has run. Inside an action or the setup function, the code runs after a component has called useCartStore(), so Pinia is active and the other store can be created or retrieved.
You register a plugin with pinia.use(), but one store doesn't get the new property. What is a likely cause?
Plugins only apply to stores created after the plugin is registered and after pinia has been installed on the app. If that store was created earlier, for example because some code called its useXStore() during setup before pinia.use() ran, it never passed through the plugin.
When would you choose a setup store over an option store?
When the store needs things only the Composition API gives you: watchers inside the store, reusing composables such as VueUse's useLocalStorage, or inject() to read app-level provides like the router. Option stores are simpler to read for plain state, getters and actions; both are fully supported.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.