Vue3 Fundamentals · State Management with Pinia

Defining a store

defining a store with defineStore

Defining a store

Several components need the same data: a cart, the signed-in user, a theme. Passing it down through props gets awkward, and provide / inject only reaches a subtree. Pinia gives you a store: one reactive container that any component can read and write.

You define a store with defineStore. It takes a unique id and an options object holding state, getters, and actions:

import { defineStore } from 'pinia';

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

Two details matter. The id — 'counter' here — must be unique across the app; it is how Pinia tells stores apart. And state is a function that returns the initial state, not the state object itself, so each store instance starts fresh.

defineStore returns a function, conventionally named useCounterStore. You call it to get the store instance. The name starts with use so it reads like the composables it behaves like.

You are about to answer a short quiz on defining a store.

  1. The first argument to `defineStore` is the store's unique id.
  2. In an options store, `state` is the initial state object itself, not a function.
  3. The options-store `state` option must be a ___ that returns the initial state.
  4. You define a store by calling `defineStore` with a unique id and an options object containing `state`, `getters`, and ___.
  5. A store's id must be unique across the app.