Skip to content
Tutorials Center
My learning

Topics

Lesson 45 of 87 ยท State Management

Pinia

Learn Pinia, the official Vue store library. Define options and setup stores, use state, getters and actions, keep reactivity with storeToRefs and try a runnable plain-Vue stand-in.

In the last lesson you built a store by hand from reactive, computed and plain functions. Pinia is the official library that packages exactly that idea and adds what a real application needs: one store instance per app, Vue DevTools support, hot reloading, server-side rendering support, plugins and first-class TypeScript types. It replaced Vuex as the recommended state library for Vue 3.

Pinia cannot run in this site's examples, because the runner has no npm packages. So this lesson works in two layers. The Pinia code is shown read-only, exactly as you would write it in a project. Next to it, you get a runnable stand-in: about thirty lines of plain Vue that mimic defineStore and storeToRefs closely enough to run the same style of store. The stand-in is for learning how the pieces fit together; it is not a replacement for the library.

Installing and creating the Pinia instance

In a project created with npm create vue@latest you can tick the Pinia option, or add it later with npm install pinia. You then create one Pinia instance and install it as a plugin (see plugins):

JavaScript
// main.js
import { createApp } from "vue";
import { createPinia } from "pinia";
import App from "./App.vue";

createApp(App).use(createPinia()).mount("#app");

The Pinia instance is the container that holds every store of this app. Because it belongs to the app and not to the module, each app (and each server request) gets its own stores. That solves the singleton problem from the previous lesson.

Defining a store

defineStore(id, definition) takes a unique id (used by DevTools and as the key in the container) and returns a useXxxStore function. By convention the file is stores/counter.js, the function is named useCounterStore and the id matches the file. The definition comes in two flavours.

Options syntax

The options form looks like the Options API: state is a function returning the initial object, getters are derived values and actions are methods.

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

export const useCounterStore = defineStore("counter", {
  state: () => ({
    count: 0,
    step: 1,
  }),
  getters: {
    double: (state) => state.count * 2,
    summary() {
      return `count ${this.count}, double ${this.double}`;
    },
  },
  actions: {
    increment() {
      this.count += this.step;
    },
  },
});

A getter receives the state as its first argument. A regular-function getter can also use this to reach other getters. Actions use this to read and write the state, and they may be async.

Setup syntax

The setup form passes a function, just like setup(): ref and reactive become state, computed becomes getters and functions become actions. You must return everything you want the store to expose.

JavaScript
// stores/todos.js
import { ref, computed } from "vue";
import { defineStore } from "pinia";

export const useTodoStore = defineStore("todos", () => {
  const todos = ref([]);
  const remaining = computed(() => todos.value.filter((t) => !t.done).length);

  function add(text) {
    todos.value.push({ id: Date.now(), text, done: false });
  }

  return { todos, remaining, add };
});
flowchart LR
    subgraph O["Options store"]
        O1["state: () => ({ ... })"]
        O2["getters: { ... }"]
        O3["actions: { ... }"]
    end
    subgraph S["Setup store"]
        S1["ref() / reactive()"]
        S2["computed()"]
        S3["function"]
    end
    O1 --- S1
    O2 --- S2
    O3 --- S3

The two syntaxes describe the same three things. Pick the one that matches how you already write components.

Setup stores are more flexible (you can use watchers and composables inside), but they have two small differences. Pinia can only reset an options store for you with $reset(), and in a setup store you write your own reset function. And anything you forget to return is invisible to DevTools and to the rest of the app.

Using a store in a component

Call the use function inside setup() (or <script setup>) and use the returned store object like a reactive object:

VUE
<script setup>
import { storeToRefs } from "pinia";
import { useCounterStore } from "@/stores/counter";

const counter = useCounterStore();

// Destructuring state or getters directly loses reactivity:
// const { count } = counter;   // a plain number, never updates

// storeToRefs keeps them reactive. Actions can be destructured as they are.
const { count, double } = storeToRefs(counter);
const { increment } = counter;
</script>

<template>
  <button @click="increment">{{ count }} (double {{ double }})</button>
</template>

The store is a reactive object, so the rules from reactive objects apply: copying a property out of it copies a value. storeToRefs(store) returns refs for the state and getters only (it skips actions), so destructuring from it is safe. Actions are plain functions bound to the store, so you destructure those from the store itself.

Other things you will use soon:

  • counter.count++ or counter.$patch({ count: 10, step: 2 }) change state. A patch applies several changes in one update; $patch also accepts a function for arrays.
  • counter.$reset() restores the initial state of an options store.
  • counter.$subscribe(callback) runs when the state changes, for example to save it somewhere.
  • A store may call another store inside an action or getter: const user = useUserStore().
  • Calling useXxxStore() outside a component (in a router guard, say) works once app.use(pinia) has run.

A runnable stand-in

The stand-in below is deliberately small. defineStore creates the store lazily the first time useStore() is called, and returns the same instance afterwards. For options definitions it builds a reactive object from state(), adds each getter as a computed and each action bound to the store. For setup definitions it wraps what the function returns in reactive, so that refs unwrap just as they do on a real Pinia store.

An options store with a stand-in defineStore

Press increment() a few times, then $patch({ step: 5 }) and increment again: the step changes the amount added, and the summary getter (which uses this.double) stays in sync. $reset() brings back the initial state.

Now the setup syntax together with storeToRefs. This example also shows the trap that storeToRefs exists to avoid: a value copied out of the store in setup() is just a number.

A setup store and storeToRefs

Toggle a todo or add one. The first count follows the store because it is a ref created by storeToRefs. The second was read once while setup() ran, so it stays at 1 forever. That is the same mistake as destructuring state in <script setup>, and the reason the Pinia docs tell you to use storeToRefs.

What the stand-in leaves out

Do not mistake the stand-in for Pinia. The real library adds:

  • an application-level container, so each app and each server request has its own stores and server-rendered state can be handed to the browser;
  • Vue DevTools support with time travel, store inspection and edit-in-place;
  • hot module replacement while you edit a store file;
  • $subscribe, $onAction and plugins (for example for persisting state);
  • complete TypeScript inference for state, getters and actions.

When you start a real project, use Pinia. For small apps or libraries that want zero dependencies, the hand-built store from the last lesson is still perfectly fine.

Advanced Pinia: setup stores, plugins and persistence

Once the basics are comfortable, four features cover most of what real applications need.

Setup stores

Besides the options form (state, getters, actions), defineStore accepts a setup function, exactly like a component's setup: every ref becomes state, every computed becomes a getter, every function becomes an action, and you must return all of them (private values you leave out are not part of the store). It is more flexible, because you can use watch, composables and inject inside it, but it has trade-offs: $reset() does not work for setup stores (you write your own reset), and forgetting to return a ref silently breaks DevTools and SSR.

JavaScript
export const useCartStore = defineStore("cart", () => {
  const items = ref([]);
  const count = computed(() => items.value.length);
  function add(item) {
    items.value.push(item);
  }
  return { items, count, add };
});

Composing stores

A store may use another store. Call useOtherStore() inside a getter, an action or the setup function body, never at the top of the module, and avoid two stores reading each other's state while they are being created, which would loop.

JavaScript
export const useCheckoutStore = defineStore("checkout", () => {
  const cart = useCartStore();
  const user = useUserStore();
  const canPay = computed(() => user.isLoggedIn && cart.count > 0);
  return { canPay };
});

Reacting to changes: $subscribe and $onAction

  • store.$subscribe((mutation, state) => { ... }) runs after the state changes. It is the hook for saving to storage or syncing to a server.
  • store.$onAction(({ name, args, after, onError }) => { ... }) runs before an action, and lets you register callbacks for success (after) or failure (onError). It is the hook for logging, analytics and timing.

Plugins and persisted state

A plugin is a function that Pinia calls once for every store it creates, with the store in its context. It can add properties, subscribe to changes and read options. Registering one is a single line (pinia.use(myPlugin)). The classic plugin is persistence: restore the state when a store is created and save it on each change. The community package pinia-plugin-persistedstate does this for you (configured per store); the code is small enough to write yourself:

JavaScript
function persistPlugin({ store }) {
  const saved = localStorage.getItem("pinia-" + store.$id);
  if (saved) {
    store.$patch(JSON.parse(saved));
  }
  store.$subscribe((mutation, state) => {
    localStorage.setItem("pinia-" + store.$id, JSON.stringify(state));
  });
}
pinia.use(persistPlugin);

Persist only what is safe and useful: UI preferences and carts, never passwords or tokens that should not sit in localStorage (see security). The runner's preview cannot use localStorage, so the next example uses a stand-in with the same shape as the real API: defineStore, $subscribe, $onAction and plugins, with a plain object as the "storage". It is a model, not Pinia, but the plugin functions you write in it are the ones you would write for the real library.

Plugins, $subscribe and $onAction (stand-in)

Add two items, then press Simulate page reload: the store is created again from scratch and the persistence plugin restores the items from the stand-in storage. The second plugin logs every action without the store knowing about it. That separation is the point of plugins: cross-cutting features live in one function and apply to every store.

Pinia and server-side rendering

On the server, each request needs its own Pinia instance, because module-level state would leak between users (SSR and hydration). After rendering, the server serializes pinia.state.value into the HTML and the browser assigns it back before mounting, so the client starts with the same data and does not refetch it. Two rules follow: never keep user data in a plain module variable, and call useStore() only where a Pinia instance is active (inside components, or pass pinia explicitly, for example in a router guard). Browser-only plugins such as persistence must skip the server, where localStorage does not exist.

When a Pinia store is the right tool

Reach for a store when state is shared by distant components, must survive route changes, or needs the same rules in many places: the signed-in user, a shopping cart, a notification queue. Keep state local when only one component needs it, and use props, emits and provide and inject for relationships inside one feature. A good store is small and focused; several small stores that call each other beat one giant store.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the first argument of defineStore() do?

    defineStore takes a unique id first and the definition second. The id identifies the store inside the Pinia instance and in DevTools.
  2. 2. In a Pinia setup store, what must you do with the refs, computed values and functions you want to expose?

    A setup store is a function like setup(). Only what it returns becomes part of the store, so a forgotten ref is invisible to components and DevTools.
  3. 3. A component does const { count } = useCounterStore(). The button that increments the store works, but the displayed count never changes. Why?

    A store is a reactive object. Destructuring a primitive property copies its current value. Use storeToRefs(store) to get refs for state and getters, or read store.count directly.
  4. 4. Which members does storeToRefs() return refs for?

    storeToRefs makes refs for state and getters. Actions are plain functions, so you destructure them from the store itself.

Summary

  • Pinia is the official Vue state library: one container per app, DevTools support, plugins and TypeScript types.
  • defineStore(id, definition) returns a useXxxStore() function; the definition is either an options object (state, getters, actions) or a setup function that returns what to expose.
  • Use the store like a reactive object; destructure state and getters with storeToRefs, and actions straight from the store.
  • $patch, $reset and $subscribe cover batch changes, resetting and reacting to changes.
  • The stand-in on this page shows the mechanics with plain reactive and computed; use the real library in projects.
  • Keep stores small and use them for state that several distant components share.

Next: Fetching Data