Pinia fundamentals
Install Pinia, define an option store with state, getters and actions, use it in components, and keep reactivity intact with storeToRefs.
Pinia fundamentals
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- Pinia is installed as a Vue plugin with app.use(createPinia()); since Pinia 4 you also install @vue/devtools-api next to it.
- defineStore takes a unique id and a definition, and returns a useXStore function; the store itself is created lazily, the first time that function is called.
- An option store maps directly onto the Options API: state is data, getters are computed, actions are methods, and inside getters and actions this is the store.
- The store is a reactive object, so destructuring it breaks reactivity; storeToRefs turns its state and getters into refs, while actions can be destructured directly.
- State can be changed directly, in batches with $patch, reset with $reset in option stores, and observed with $subscribe; every change shows up in Vue Devtools.
A component that is always mounted
The previous lesson ended with the case for a real store. Pinia’s own docs offer a good mental model for what one is: a component that is always there, has no template, and that every other component can read from and write to. It holds state, it derives values from that state, and it has methods that change it.
If that sounds like a component’s data, computed, and methods, that is deliberate. Pinia’s first store style, the option store, borrows the shape of the Options API so the three concepts are obvious.
Installing Pinia
Pinia is a Vue plugin. You create one Pinia instance and install it on the app:
npm install pinia @vue/devtools-api
// main.js
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
const app = createApp(App)
app.use(createPinia())
app.mount('#app')
The second package is new in Pinia 4 (July 2026). The devtools integration used to ship inside Pinia; it is now a required peer dependency you install yourself, to keep Pinia’s own install small. Pinia 4 is also ESM-only. The store API itself did not change between Pinia 2, 3, and 4, so any tutorial using defineStore('name', ...) still applies.
create-vue (npm create vue@latest) offers to add Pinia when you scaffold a project and sets this up for you.
Defining an option store
// stores/cart.js
import { defineStore } from 'pinia'
export const useCartStore = defineStore('cart', {
state: () => ({
items: [],
couponCode: null,
}),
getters: {
itemCount: (state) => state.items.reduce((n, item) => n + item.qty, 0),
subtotal: (state) =>
state.items.reduce((sum, item) => sum + item.price * item.qty, 0),
total() {
// other getters are reached through `this`
return this.couponCode === 'HALF' ? this.subtotal / 2 : this.subtotal
},
},
actions: {
add(product) {
const line = this.items.find((i) => i.id === product.id)
if (line) line.qty++
else this.items.push({ ...product, qty: 1 })
},
async applyCoupon(code) {
const res = await fetch(`/api/coupons/${code}`)
if (!res.ok) throw new Error('Invalid coupon')
this.couponCode = code
},
},
})
A few things to notice:
- The id (
'cart') must be unique across the app. Pinia uses it to register the store and to label it in devtools. The convention is to name the exported functionuse+ id +Store. stateis a function returning the initial object, for the same reason a component’sdatais: every Pinia instance gets a fresh copy.- Getters receive
stateas an argument and are cached likecomputed. A getter that needs another getter usesthisinstead, astotaldoes. - Actions are plain methods.
thisis the store, so they read and write state directly, call getters, and can beasync. No ceremony separates “sync” and “async” changes.
Using the store in a component
defineStore doesn’t create anything. It returns a function, and the store is created the first time that function is called while a Pinia instance is active:
<script setup>
import { storeToRefs } from 'pinia'
import { useCartStore } from '@/stores/cart'
const cart = useCartStore()
const { items, itemCount, total } = storeToRefs(cart)
const { add } = cart
</script>
<template>
<p>{{ itemCount }} items · {{ total }}</p>
<button @click="add({ id: 7, name: 'Mug', price: 12 })">Add mug</button>
</template>
Every component calling useCartStore() gets the same store instance.
The destructuring trap, and storeToRefs
The store is a reactive() object, which means the same rule from ref and reactive applies: pulling a property out of it gives you a plain value, frozen at that moment.
const { itemCount } = useCartStore() // a number, never updates
storeToRefs(store) solves this by returning a ref for every piece of state and every getter, each linked back to the store. Actions are skipped, because they’re just functions and destructuring them directly is fine. You can also avoid destructuring altogether and write cart.itemCount in the template.
Changing state
You have four tools, from simplest to most deliberate:
const cart = useCartStore()
// 1. Direct assignment: allowed, and tracked by devtools
cart.couponCode = 'HALF'
// 2. $patch with an object: several fields as one change
cart.$patch({ couponCode: null, items: [] })
// 3. $patch with a function: for changes that read current state
cart.$patch((state) => {
state.items.push({ id: 9, name: 'Pen', price: 2, qty: 1 })
})
// 4. An action: the place for logic you want to name and reuse
cart.add({ id: 9, name: 'Pen', price: 2 })
Direct writes are legal in Pinia, unlike in Vuex. In practice, putting anything more than a trivial assignment behind an action keeps the rules for changing state in one file.
Two more built-ins round this out. cart.$reset() restores the initial state by calling state() again; it exists only on option stores. cart.$subscribe((mutation, state) => { ... }) runs a callback after every state change, which is the simplest way to, say, save the cart to localStorage on each change. A subscription made inside a component is removed when that component unmounts.
Devtools
Open Vue Devtools and there is a Pinia panel listing every created store, its state and getters, and a timeline of actions and patches. You can edit state live. This visibility is a large part of why a store beats a hand-rolled module-level object, and it is covered further in debugging with Vue Devtools.
What the video covers
The embed runs from the “Adding Pinia” chapter (8:24) to the end of “Cross-component state sharing” (36:41) in DotNetMastery’s 2025 Pinia tutorial. It builds a small score game: app.use(createPinia()), an option store defined as defineStore('gameStore', { state, getters, actions }), and <script setup> components that call useGameStore() and change state directly. One useful detour: a getter that returns a random number keeps returning the same value, because getters are cached like computed, and that is the cue to move the logic into actions. It ends with a second component reading and editing the same store through v-model.
It skips storeToRefs, $patch, $reset, and $subscribe, so the destructuring and state-change sections above carry those. If you see defineStore({ id: 'name', ... }) in older material, that form was removed in Pinia 3; pass the id as the first argument, as this video does.
Where this fits
The next lesson, Pinia setup stores and plugins, writes the same store with the Composition API and shows how to extend every store at once.
Check yourself
In a component, you write const { count, increment } = useCounterStore(), and the template showing count never updates. Why, and what's the fix?
The store is a reactive object, and destructuring copies the current value of count into a plain local variable, cutting it off from reactivity. Use const { count } = storeToRefs(store) to get a ref that stays linked to the store, and destructure actions like increment directly from the store, since functions don't need to be reactive.
What is the difference between a getter and an action in an option store?
A getter is a derived value, cached like a computed property and recalculated only when the state it reads changes; it should not cause side effects. An action is a method that can change state, call other stores, and be asynchronous, such as calling an API and then writing the result into state.
Why would you use $patch with a function instead of assigning three state properties one after another?
$patch groups the changes into a single entry, so Vue Devtools shows one mutation and $subscribe fires once instead of three times. The function form is also the natural way to apply changes that need to read current state, such as pushing into an array, without replacing the array.
A store is defined in stores/cart.js, but it only exists after some component calls useCartStore(). Why does Pinia work this way?
defineStore only describes the store and returns a function. The store is created the first time that function runs with an active Pinia instance, which keeps unused stores out of memory and ties each store to a specific Pinia instance, which is what makes per-request stores possible under server-side rendering.
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.