Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 38 ยท Stores and State

Organizing Stores

Decide what belongs in a Pinia store and what does not. Learn naming, file layout, store size, normalized state and when to keep state local to a component instead.

Pinia makes stores so cheap to create that the hard question is no longer "how" but "what". This lesson gives practical rules for deciding what goes into a store, how to split stores, and how to lay out files so a large app stays easy to read.

Not everything belongs in a store

A store is global state. Every global thing is harder to reason about than a local one, so put state in a store only when at least one of these is true:

  • Several distant components need it (the signed-in user, a cart, a theme).
  • It must survive navigation (a draft, filters on a list page).
  • It is shared with non-component code (API helpers, router guards).

Everything else should stay in the component with ref: whether a dropdown is open, the text in a search box that nothing else reads, hover state. Putting those in a store adds indirection and nothing else.

flowchart TD
    A["New piece of state"] --> B{"Used by more than<br/>one distant component?"}
    B -->|"No"| C["ref() in the component"]
    B -->|"Yes"| D{"Needs to survive<br/>navigation?"}
    D -->|"No, only parent and children"| E["props / provide-inject"]
    D -->|"Yes, or used outside components"| F["Pinia store"]

Local first, then props or provide/inject, and a store last.

One store per domain

The most reliable way to split stores is by domain concept, the nouns of your app: useUserStore, useCartStore, useProductsStore, useNotificationsStore. Each store owns one idea and exposes what the rest of the app needs about it.

Avoid splitting by technical layer:

  • A useStateStore plus a useGettersStore defeats the purpose of stores.
  • One giant useAppStore with 40 properties becomes a junk drawer that everything depends on.

A good size is something you can describe in one sentence ("the items in the cart and what they cost") without using the word "and" more than once or twice.

Naming conventions

Pinia does not force names, but the community convention keeps code searchable:

Thing Convention Example
Use function use + name + Store useCartStore
Store id lowercase, matches the domain "cart"
File name + .js or .ts stores/cart.js
Actions verbs addItem, checkout, loadProducts
Getters nouns or adjectives totalPrice, isEmpty

Make the id unique. Two stores with the same id overwrite each other silently and DevTools shows one of them.

A folder layout

For small and medium apps, a flat folder is enough:

TEXT
src/
  stores/
    user.js
    cart.js
    products.js
    notifications.js
  components/
  views/

Large apps often co-locate stores with their feature:

TEXT
src/
  features/
    cart/
      cart.store.js
      CartView.vue
      CartItem.vue
    auth/
      auth.store.js
      LoginView.vue

Either is fine. Pick one and be consistent. Do not put several stores in one file; one export const useXStore per file keeps imports predictable and works well with hot reloading.

Keep state minimal, derive the rest

State should hold the smallest set of facts that cannot be computed. Everything else is a getter. Compare:

JavaScript
// Redundant: three values that must be kept in sync
state: () => ({ items: [], count: 0, total: 0 })

// Better: one fact, two derived values
state: () => ({ items: [] }),
getters: {
  count: (state) => state.items.length,
  total: (state) => state.items.reduce((sum, i) => sum + i.price * i.qty, 0),
}

Every duplicated value is a bug waiting for the day one copy updates and the other does not.

Normalize shared collections

If the same entity appears in several lists, store each entity once, keyed by id, and keep lists as arrays of ids:

JavaScript
state: () => ({
  byId: {},        // { 1: { id: 1, title: "..." }, 2: { ... } }
  featuredIds: [], // [1, 4]
  recentIds: [],   // [4, 2]
}),
getters: {
  featured: (state) => state.featuredIds.map((id) => state.byId[id]),
},

Now editing product 4 updates it in both lists, because there is one copy. Try the pattern below: the same product is in two lists, and renaming it changes both.

A normalized products store

Keep side effects in actions

Components should read state and call actions. Fetching, validation, calling other stores and navigation belong in actions, not in components. That keeps components short and makes the logic testable without rendering anything (you will do exactly that in the testing chapter).

A rule of thumb for reviews: if a component writes to three different stores in one click handler, that handler wants to be an action.

Stores that depend on each other

Stores may use one another, but keep the graph a tree. If cart reads user, user must not also read cart. If you find a cycle, a third store or a plain function usually dissolves it. Stores using other stores shows the safe patterns.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which state is best kept in the component, not a store?

    State used by a single component and nothing else should stay local.
  2. 2. How should stores usually be split?

    Domain stores own one idea each. Splitting by technical layer or lumping everything together makes code hard to follow.
  3. 3. Why normalize shared collections?

    With a byId map and lists of ids, there is a single copy of each entity to update.
  4. 4. Where should fetching and cross-store logic live?

    Actions hold side effects, which keeps components thin and logic easy to test.

Summary

  • Use a store only for state that is shared widely, must survive navigation or is used outside components.
  • Split stores by domain concept; name them useXStore with a short unique id.
  • Keep state minimal and derive the rest in getters.
  • Normalize entities shared by several lists.
  • Put side effects in actions, and keep dependencies between stores acyclic.

Next: Getters