TExcelTAD
Home › Vue › Vue State Management (Pinia)

Vue State Management (Pinia)

As an app grows, some data is needed by many components that are not related: the logged-in user, the shopping cart, notification counts, settings. Passing it through props and events across the whole tree becomes messy. The solution is a store: a single, shared place that holds this state and the functions that change it. Any component can read from it and call its actions.

Pinia is Vue's official state management library (it replaced Vuex). It's small, type-safe and works with Vue DevTools.

Pinia concepts

Concept Like… Purpose
State data The shared reactive data
Getters computed Values derived from state, cached
Actions methods Functions that change state, may be async

Defining a store

Install with npm install pinia (or tick "Pinia" in npm create vue@latest) and register it:

js
// main.js
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'

createApp(App).use(createPinia()).mount('#app')

A store is defined with defineStore(id, …). There are two syntaxes. The options store looks like the Options API:

js
// stores/cart.js
import { defineStore } from 'pinia'

export const useCartStore = defineStore('cart', {
  state: () => ({ items: [] }),
  getters: {
    count: (state) => state.items.reduce((n, i) => n + i.qty, 0),
    total: (state) => state.items.reduce((s, i) => s + i.qty * i.price, 0)
  },
  actions: {
    add(product) {
      const line = this.items.find(i => i.id === product.id)
      line ? line.qty++ : this.items.push({ ...product, qty: 1 })
    }
  }
})

The setup store looks like a composable — refs are state, computeds are getters, functions are actions:

js
export const useCartStore = defineStore('cart', () => {
  const items = ref([])
  const count = computed(() => items.value.reduce((n, i) => n + i.qty, 0))
  function add(product) { /* … */ }
  return { items, count, add }
})

Using it in any component:

vue
<script setup>
import { storeToRefs } from 'pinia'
import { useCartStore } from '@/stores/cart'

const cart = useCartStore()
const { count, total } = storeToRefs(cart)   // keep reactivity when destructuring state/getters
const { add } = cart                          // actions can be destructured directly
</script>

<template>
  <p>{{ count }} items — {{ total }} €</p>
  <button @click="add({ id: 1, name: 'Tea', price: 3 })">Add tea</button>
</template>

The idea without Pinia

Pinia's core is something you can build with reactive() alone: a module-level reactive object is shared by everyone who imports it. In the playground, two unrelated components — a product list and a cart badge — share one store.

html · try it yourself
<style>
  header { display: flex; justify-content: space-between; background: #1f2937; color: white; padding: 8px 12px; font-family: sans-serif; }
  .product { display: flex; justify-content: space-between; max-width: 300px; padding: 4px 0; }
</style>

<div id="app">
  <cart-badge></cart-badge>
  <product-list></product-list>
  <cart-panel></cart-panel>
</div>

<script type="module">
  import { createApp, reactive, computed, readonly } from 'vue';

  // --- the "store" (in a real app: stores/cart.js) ---
  const state = reactive({ items: [] });
  const cartStore = {
    state: readonly(state),                                   // components can read…
    count: computed(() => state.items.reduce((n, i) => n + i.qty, 0)),
    total: computed(() => state.items.reduce((s, i) => s + i.qty * i.price, 0)),
    add(product) {                                            // …but only actions write
      const line = state.items.find(i => i.id === product.id);
      line ? line.qty++ : state.items.push({ ...product, qty: 1 });
      console.log('add', product.name);
    },
    clear() { state.items = []; }
  };

  const app = createApp({});

  app.component('cart-badge', {
    setup: () => ({ count: cartStore.count }),
    template: `<header><b>☕ TAD Tea</b><span>🛒 {{ count }}</span></header>`
  });

  app.component('product-list', {
    setup: () => ({
      products: [
        { id: 1, name: 'Green tea', price: 4 },
        { id: 2, name: 'Oolong', price: 6.5 },
        { id: 3, name: 'Jasmine', price: 5 }
      ],
      add: cartStore.add
    }),
    template: `
      <div class="product" v-for="p in products" :key="p.id">
        {{ p.name }} ({{ p.price }} €) <button @click="add(p)">Add</button>
      </div>`
  });

  app.component('cart-panel', {
    setup: () => ({ cart: cartStore }),
    template: `
      <h4>Cart</h4>
      <p v-if="!cart.state.items.length">Empty.</p>
      <p v-for="i in cart.state.items" :key="i.id">{{ i.qty }} × {{ i.name }}</p>
      <p><b>Total: {{ cart.total.value.toFixed(2) }} €</b> <button @click="cart.clear()">Clear</button></p>`
  });

  app.mount('#app');
</script>

Note cart.total.value: the computed is nested inside a plain object, so the template doesn't unwrap it automatically. Pinia stores are reactive() objects, so with real Pinia you'd simply write cart.total.

Why use Pinia instead of a plain reactive object?

Feature Plain reactive() module Pinia
Shared state ✅ ✅
DevTools: timeline of actions, state inspection, time travel ❌ ✅
Hot module replacement keeping state ❌ ✅
Server-side rendering safe (one store per request) ❌ module state leaks between requests ✅
Plugins (persisting to storage, undo…) ❌ ✅
$reset(), $patch(), $subscribe() ❌ write yourself ✅ built in

A second example: a settings store with persistence

A setup-style store, simulated with a composable-like function. watch stands in for a "persist" plugin, recording each saved snapshot:

html · try it yourself
<div id="app">
  <settings-form></settings-form>
  <preview-box></preview-box>
</div>

<script type="module">
  import { createApp, ref, watch } from 'vue';

  // setup-store style: refs + functions, created once and shared
  const fontSize = ref(16);
  const accent = ref('#42b883');
  const saved = [];
  watch([fontSize, accent], ([f, a]) => {
    saved.push({ fontSize: f, accent: a });
    console.log('persisted settings #' + saved.length, JSON.stringify(saved[saved.length - 1]));
  });
  const useSettings = () => ({ fontSize, accent, reset: () => { fontSize.value = 16; accent.value = '#42b883'; } });

  const app = createApp({});
  app.component('settings-form', {
    setup: () => useSettings(),
    template: `<p>Size <input type="range" min="12" max="28" v-model.number="fontSize">
               Accent <input type="color" v-model="accent"> <button @click="reset">Reset</button></p>`
  });
  app.component('preview-box', {
    setup: () => useSettings(),
    template: `<p :style="{ fontSize: fontSize + 'px', borderLeft: '6px solid ' + accent, paddingLeft: '8px' }">
                 Preview text at {{ fontSize }}px</p>`
  });
  app.mount('#app');
</script>

Tip: Keep local state (an input's text, whether a dropdown is open) in the component. Put state in a store only when several distant components need it.

Note: Destructuring a Pinia store directly (const { count } = useCartStore()) breaks reactivity for state and getters. Use storeToRefs(store) for those; actions are plain functions and can be destructured safely.

Test yourself

In Pinia, what are getters most similar to?

  1. Methods
  2. Computed properties
  3. Props
  4. Watchers

How do you destructure state from a Pinia store without losing reactivity?

  1. const { a } = store
  2. const { a } = toRaw(store)
  3. const { a } = storeToRefs(store)
  4. const { a } = store.$state

When should data go into a global store?

  1. Always, for every piece of state
  2. When several unrelated components need to share it
  3. Only for form inputs
  4. Never; use props instead