Tech Interview RoomStudy guides

Vue.js

How does state management work with Pinia?

Intermediate · 2 min read · Lesson 8 of 12 in Vue.js

Pinia is Vue's official state library (it replaced Vuex). A store is a reactive object with:

  • state: the data.
  • getters: computed values from state.
  • actions: methods (sync or async) that change state. There are no mutations as in Vuex.

Two styles

  • Options store: defineStore('cart', { state, getters, actions }).
  • Setup store: defineStore('cart', () => { ...refs, computeds, functions; return {...} }), written like a composable.

Using a store

const cart = useCartStore() in a component. Do not destructure state directly (it loses reactivity); use storeToRefs(cart) for state and getters, and destructure actions normally.

Why Pinia over Vuex

Full TypeScript inference without wrappers, no mutations boilerplate, modular stores by design (no nested modules), DevTools support with time travel, and plugins (for example persisting to localStorage). It works with SSR (one store instance per request).

What belongs in a store

Global client state: the logged-in user, cart, UI preferences, cross-page wizards. Server data is often better handled by TanStack Query for Vue or Nuxt's useFetch, which cache and refetch for you.

Example

js
// stores/cart.js
import { defineStore } from 'pinia';
import { ref, computed } from 'vue';

export const useCartStore = defineStore('cart', () => {
  const items = ref([]);
  const count = computed(() => items.value.reduce((n, i) => n + i.qty, 0));
  const total = computed(() => items.value.reduce((s, i) => s + i.qty * i.price, 0));

  function add(product) {
    const line = items.value.find(i => i.id === product.id);
    line ? line.qty++ : items.value.push({ ...product, qty: 1 });
  }
  async function checkout() {
    await fetch('/api/orders', { method: 'POST', body: JSON.stringify(items.value) });
    items.value = [];
  }
  return { items, count, total, add, checkout };
});
vue
<script setup>
import { storeToRefs } from 'pinia';
import { useCartStore } from '@/stores/cart';
const cart = useCartStore();
const { count, total } = storeToRefs(cart);   // keeps reactivity
const { add } = cart;                         // actions can be destructured
</script>
<template>🛒 {{ count }} · ₹{{ total }}</template>

Follow-up questions interviewers ask

Try answering each one before you open it.

How do you test a Pinia store?

Create a fresh Pinia per test with setActivePinia(createPinia()), then call actions and assert state; mock fetch with MSW or vi.fn(). For component tests, createTestingPinia() from @pinia/testing stubs actions and lets you set the initial state.