Setting Up State Management (Pinia) for Vue Application
Pinia is the official state management for Vue 3. Simple API similar to Zustand, built on composition API, full TypeScript support. Stores are defined as composables, no need for separate files or boilerplate.
Replaces Vuex as the recommended state management solution for Vue 3.
What's Involved
Creating stores with Pinia, organizing state, actions, and getters, integrating with Vue Router, devtools setup, testing stores.
Installation
npm install pinia
Setup in main.ts:
import { createPinia } from 'pinia'
const app = createApp(App)
app.use(createPinia())
Basic Store
import { defineStore } from 'pinia'
export const useCartStore = defineStore('cart', {
state: () => ({
items: [] as CartItem[],
}),
getters: {
total: (state) => state.items.reduce((sum, i) => sum + i.price * i.qty, 0),
count: (state) => state.items.reduce((sum, i) => sum + i.qty, 0),
},
actions: {
addItem(item: CartItem) {
const existing = this.items.find(i => i.id === item.id)
if (existing) {
existing.qty++
} else {
this.items.push({ ...item, qty: 1 })
}
},
},
})
Usage in components:
<script setup>
const cart = useCartStore()
</script>
<template>
<div>
<button @click="cart.addItem(product)">Add to cart ({{ cart.count }})</button>
<span>Total: {{ cart.total }}</span>
</div>
</template>
Timeline
Basic Pinia setup — 1 hour. Multiple stores with actions — 1–2 hours. Full integration with Vue Router — 2–3 hours.







