Managing Application State with Vuex and Pinia

After this lesson you will be able to pick the right level of state management for any feature you build, write a Pinia store that other components can use without surprises, and persist part of your application state across reloads. You will also know what Vuex still does that Pinia does not, and - more importantly - when you do not need a store at all.

What counts as state

State is any value that can change over time and that the interface depends on: the number of items in a cart, the current user, whether a dialog is open, which filter is selected.

Not all state deserves the same machinery. A good rule is to start at the narrowest scope that works and widen only when a real requirement forces it.

  1. Local state - a value that only one component reads. Keep it in a ref inside that component.
  2. Lifted state - a value that a parent and its children share. Keep it in the parent, pass it down as props, listen for events.
  3. Shared logic - behaviour that several components need. Extract it into a composable.
  4. Subtree state - a value that a whole branch of the tree needs, such as a theme. Provide it with provide and inject.
  5. Application state - a value that unrelated parts of the app must agree on, such as the signed-in user or the shopping cart. This is what a store is for.

Most features never reach step five. A store that holds the state of one screen is a store you will have to maintain for no benefit.

Reactive state without a library

Before reaching for Vuex or Pinia, remember that a store is just a reactive object with a public API. Two patterns cover most needs.

A module-scoped composable. The state lives in a module, and every caller gets the same instance.

// useCart.js
import { ref, computed } from 'vue';

const items = ref([]);

export function useCart() {
  const total = computed(() =>
    items.value.reduce((sum, item) => sum + item.price * item.quantity, 0),
  );

  function add(product) {
    items.value.push({ ...product, quantity: 1 });
  }

  return { items, total, add };
}

This is a store in everything but name, and for a small application it is entirely sufficient. The limitation appears when several modules need to react to each other’s changes, or when you want devtools support, plugins and persistence for free.

provide and inject. The state is owned by an ancestor and injected by its descendants. This is scoped to a subtree, so it never leaks into unrelated parts of the app.

// in a layout component
const theme = ref('light');
provide('theme', theme);

Vuex: the classic model

Vuex was the official state management library for Vue 2, and Vuex 4 supports Vue 3. Its model is strict by design: a single store, one state tree, and a rule that state is only ever changed by a mutation.

// store/index.js
import { createStore } from 'vuex';

export const store = createStore({
  state: () => ({ count: 0 }),
  getters: {
    double: (state) => state.count * 2,
  },
  mutations: {
    increment(state, amount) {
      state.count += amount;
    },
  },
  actions: {
    async incrementAsync({ commit }, amount) {
      await doSomething();
      commit('increment', amount);
    },
  },
});

The store is installed with createApp(App).use(store).mount('#app'), and a component reaches it with useStore(). Reading a value goes through store.state.count and store.getters.double; changing it goes through store.dispatch('incrementAsync', 1), which eventually commits a mutation.

The four concepts are worth understanding, because Pinia is a simplification of the same model:

  • state - the data, a plain reactive object.
  • getters - derived values, cached until their dependencies change.
  • mutations - synchronous functions that change state. Strict mode in development warns when state is changed outside one.
  • actions - asynchronous functions that eventually commit mutations.

The friction that led to Pinia is real: the distinction between mutations and actions is hard to explain to a newcomer, every component needs useStore and store.state.x boilerplate, and TypeScript support requires hand-written helpers.

Pinia: the modern store

Pinia is the recommended state management library for Vue 3. It keeps one idea - a store holds state and exposes actions - and removes the ceremony.

npm install pinia
// 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');

An option store

// stores/counter.js
import { defineStore } from 'pinia';

export const useCounterStore = defineStore('counter', {
  state: () => ({ count: 0 }),
  getters: {
    double: (state) => state.count * 2,
    isPositive: (state) => state.count > 0,
  },
  actions: {
    increment(amount = 1) {
      this.count += amount;
    },
    reset() {
      this.count = 0;
    },
  },
});

A setup store

The setup syntax mirrors the Composition API and is usually easier to read for logic that needs computed values or composables.

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

export const useCounterStore = defineStore('counter', () => {
  const count = ref(0);
  const double = computed(() => count.value * 2);

  function increment(amount = 1) {
    count.value += amount;
  }

  function reset() {
    count.value = 0;
  }

  return { count, double, increment, reset };
});

Using a store

Inside setup, call the store function. The store instance is created on first use and then cached.

<script setup>
import { storeToRefs } from 'pinia';
import { useCounterStore } from '../stores/counter';

const counter = useCounterStore();

// Destructuring a store directly loses reactivity.
// storeToRefs keeps the state properties reactive.
const { count, double } = storeToRefs(counter);
</script>

<template>
  <p>{{ count }} / {{ double }}</p>
  <button type="button" @click="counter.increment()">Add one</button>
</template>

Destructuring the store itself is safe for actions and getters - they are functions and plain values that do not need tracking - but not for state properties. storeToRefs is the tool that keeps both kinds of property reactive.

Mutating state deliberately

$patch applies several changes at once and triggers subscribers only once, which is more efficient than a sequence of separate assignments: counter.$patch({ count: 10 }) or counter.$patch((state) => { state.count += 5; }).

$subscribe fires whenever the state changes, and $onAction fires whenever an action runs. Together they cover logging, analytics and persistence without touching the store’s own code. $reset restores the initial state and exists only for option stores, because a setup store has no recorded starting point unless you write one.

Using one store from another

A store can use another store. Call the other store’s function inside the action; Pinia resolves the order for you.

A store can use another store: inside an action, call the other store’s function - const cart = useCartStore(); await postOrder(cart.items); cart.clear(); - and Pinia resolves the order for you.

When a global store is warranted

A store is worth adding when at least one of these is true:

  • Two or more unrelated branches of the interface must agree on a value and the value outlives any single screen - the signed-in user, the cart, the notification count.
  • The value must survive navigation and remounting and no single component is a natural owner.
  • The value is derived from several sources and you want the derivation in one tested place instead of spread across components.
  • You need cross-cutting behaviour - persistence, devtools time travel, or an audit log - applied uniformly to a family of state.

If none of those hold, a ref in the right component, or a composable, is the better answer. A store has a cost: every consumer now depends on the store’s shape, renaming a field becomes a breaking change, and the state is no longer visible in the component tree.

Persisting state

The simplest persistence is a watch on the store that writes to localStorage.

// stores/persist.js
export function persistStore(store, key) {
  const saved = localStorage.getItem(key);
  if (saved) store.$patch(JSON.parse(saved));

  store.$subscribe((_mutation, state) => {
    localStorage.setItem(key, JSON.stringify(state));
  });
}

The community plugin pinia-plugin-persistedstate does the same thing declaratively.

// main.js
import { createPinia } from 'pinia';
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate';

const pinia = createPinia();
pinia.use(piniaPluginPersistedstate);
app.use(pinia);
export const usePreferencesStore = defineStore('preferences', {
  state: () => ({ theme: 'light', locale: 'en' }),
  persist: {
    key: 'app-preferences',
    // Only persist these properties, not the whole store.
    paths: ['theme', 'locale'],
  },
});

Two rules when you persist anything:

  • Do not persist tokens in localStorage if you can avoid it. It is readable by any script on the page. Use a cookie with HttpOnly, or a short-lived in-memory token.
  • Do not persist the whole store blindly. A store often holds derived values or transient flags that should start fresh on every launch.

Server-side rendering

With SSR, each request needs its own store instance, otherwise one user’s state leaks into another’s response.

Create one Pinia instance per request - const pinia = createPinia(); app.use(pinia); inside the app factory - and otherwise one user’s state leaks into another’s response.

The server serialises pinia.state.value into the page and the client restores it before the app mounts, so the first render matches.

Pitfalls to remember

  • Destructuring a store loses reactivity for state properties. Use storeToRefs.
  • Calling useSomeStore() at module scope, outside a component or action, runs before the Pinia instance exists. Call it inside setup or inside an action.
  • defineStore needs a unique id. Two stores with the same id share state silently.
  • Mutating state from outside an action makes devtools time travel and $subscribe unreliable. Keep mutations inside the store.
  • reactive state returned from a store is unwrapped on the store instance, so store.state is a plain object - do not expect toRefs to work on it.

Practice

An application has a signed-in user, a shopping cart, and a “recently viewed” list. The user is fetched once at start-up and must be available everywhere. The cart is edited from a cart badge in the header and from a cart page, and its total must be shown in both places. The recently viewed list is written from the product page and read from the home page, and it should not survive a logout.

Decide what goes into a store, what does not, and write the code.

PiniaVuexState ManagementPersistencestoreToRefs

Approach:

Look at each value and ask who needs it. The user is needed by every component and outlives every screen, so it belongs in a store. The cart is edited in two unrelated places and must show the same total in both, so it belongs in a store too - but as a cart store, not as part of the user store. The recently viewed list is written in one place and read in another, which looks like a store case, but it is derived from navigation and should be cleared when the session ends; keeping it in a store is still the right call, because the product page and the home page have no common ancestor.

Steps:

  1. Create one store per domain. useUserStore, useCartStore, useRecentlyViewedStore. Do not put everything in one “app” store; separate domains change for separate reasons.
  2. Give each store an id. The id is the key Pinia uses to cache the instance, so it must be unique.
  3. Keep derived values in getters. The cart total is computed from the items, so it must never be stored separately - a stored total can drift out of sync with the items.
  4. Expose state and actions. Return the items and the actions from a setup store; consumers use storeToRefs for the state and call the actions directly.
  5. Do not persist the user or the cart. The user comes from the server on every start-up, and the cart belongs to the session. Only the recently viewed list has a good reason to survive a reload, and even that one is cleared on logout.

Answer:

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

export const useUserStore = defineStore('user', () => {
  const user = ref(null);
  const isLoggedIn = computed(() => user.value !== null);

  async function load() {
    const response = await fetch('/api/me', { credentials: 'include' });
    user.value = response.ok ? await response.json() : null;
  }

  function logout() {
    user.value = null;
  }

  return { user, isLoggedIn, load, logout };
});
// stores/cart.js
import { ref, computed } from 'vue';
import { defineStore } from 'pinia';

export const useCartStore = defineStore('cart', () => {
  const items = ref([]);

  const total = computed(() =>
    items.value.reduce((sum, item) => sum + item.price * item.quantity, 0),
  );

  function add(product) {
    const existing = items.value.find((item) => item.id === product.id);
    if (existing) existing.quantity += 1;
    else items.value.push({ ...product, quantity: 1 });
  }

  function remove(id) {
    items.value = items.value.filter((item) => item.id !== id);
  }

  function clear() {
    items.value = [];
  }

  return { items, total, add, remove, clear };
});

The recently viewed store follows the same shape: a ids ref, a record(id) action that moves the id to the front of the list and caps it at twenty entries, and a clear() action that the logout flow calls.

<!-- CartBadge.vue -->
<script setup>
import { storeToRefs } from 'pinia';
import { useCartStore } from '../stores/cart';

const cart = useCartStore();
const { itemCount, total } = storeToRefs(cart);
</script>

<template>
  <RouterLink to="/cart">
    Cart ({{ itemCount }}) - {{ total }}
  </RouterLink>
</template>

The badge and the cart page read the same useCartStore() instance, so the count and the total are always consistent, and the recently viewed list is cleared by calling useRecentlyViewedStore().clear() inside the logout action.

More courses

Recommended courses

Found an issue with this content?

Tell us what could be improved.