Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 38 ยท Projects and Practice

Pinia Best Practices and Practice Exercises

A practical Pinia checklist: how to organize stores, what belongs in state, getters and actions, the classic reactivity mistakes, and hands-on exercises with tests to fix.

You now know the whole Pinia toolbox: stores, getters, actions, plugins, persistence, testing, SSR, Nuxt and migration. This last lesson turns that knowledge into habits. First a checklist of practices that keep stores small and predictable, then the mistakes that trip up almost everybody (with runnable proof), and finally exercises where you fix broken stores until the tests pass.

Best practices

1. One store per domain concept

A store should answer one question: "what do we know about X?" (the user, the cart, the notifications). A single giant appStore becomes the old Vuex root store again. If a store grows past a few hundred lines or mixes unrelated things, split it.

2. Keep state minimal and derive the rest

Store the smallest set of facts and compute everything else:

JavaScript
// avoid: three values that must stay in sync
state: () => ({ items: [], count: 0, isEmpty: true })

// prefer: one fact, two getters
state: () => ({ items: [] }),
getters: { count: (s) => s.items.length, isEmpty: (s) => s.items.length === 0 }

Every duplicated value is a future bug.

3. Put rules in actions, not in components

Validation, calculations that change state and API calls belong in actions. Components call store.add(item) and display results. This keeps components thin and makes the rules testable without a DOM.

4. Name things clearly

Stores: useXStore, ids in lowercase singular or plural nouns ("cart"). Actions: verbs (addItem, load, checkout). Getters: nouns or adjectives (total, isEmpty). State: nouns.

5. Keep state serializable

Plain objects, arrays, strings, numbers, booleans and null. This keeps DevTools, SSR and persistence working. Keep functions, class instances, DOM nodes and promises out of state.

6. Model loading and error states explicitly

Every async action should have a visible lifecycle: idle, loading, success, error. Prefer a single status string over several booleans that can contradict each other (loading and error both true).

7. Use storeToRefs for state and getters

Destructure actions freely, but wrap state and getters (see the exercise below). In templates you can also just use store.count without destructuring at all.

8. Call stores at the right time

Call useXStore() inside setup, actions, getters, guards and plugins, never at module top level. In SSR pass the pinia when you are outside a component.

9. Avoid cyclic store dependencies

If store A uses B at import time and B uses A, you get confusing errors. Call other stores inside actions and getters, not at the top of the file, and keep dependencies one-directional.

10. Reset and persist deliberately

Clear private data on logout. Persist only what you must (preferences, drafts), never secrets, and version the saved shape.

11. Test the store, not the framework

A few focused store tests (see the testing chapter) give more safety than many component tests.

12. Do not store everything globally

State used by one component belongs in that component (ref). Global stores are for data shared across distant parts of the app. A store used by only one component is usually a sign of over-engineering.

flowchart TD
  Q["Where should this state live?"] --> A{"Used by one component only?"}
  A -->|"yes"| L["local ref / reactive"]
  A -->|"no"| B{"Shared by parent and a few children?"}
  B -->|"yes"| P["props / provide-inject / composable"]
  B -->|"no, many places or routes"| S["Pinia store"]

A quick decision tree.

The classic mistakes, running

Run this. It shows three mistakes and the fix for each, with a small log instead of a UI.

Destructuring, replacing and mutating: what breaks

Summary of the three: destructure with storeToRefs, patch rather than replace ($patch/$state keep references valid), and derive, do not copy.

Practice: fix the store

Below is a deliberately broken wishlist store and a set of tests that currently fail. Edit the store until all five tests print PASS. The tests are the specification:

  1. add ignores duplicates.
  2. add trims the name and ignores empty names.
  3. remove deletes by name.
  4. count is a getter, not duplicated state.
  5. clear empties the list and returns the number of removed items.
Exercise: make the wishlist tests pass

When you are done, compare with this solution (try to solve it first):

JavaScript
const useWishlistStore = defineStore("wishlist", {
  state: () => ({ items: [] }),
  getters: {
    count: (state) => state.items.length,
  },
  actions: {
    add(name) {
      const clean = name.trim();
      if (!clean || this.items.includes(clean)) return false;
      this.items.push(clean);
      return true;
    },
    remove(name) {
      this.items = this.items.filter((n) => n !== name);
    },
    clear() {
      const removed = this.items.length;
      this.items = [];
      return removed;
    },
  },
});

More practice ideas

  1. Notifications store: push(message, type), automatic removal after a timeout, a getter that returns only errors.
  2. Theme store with persist of the theme only, applying a class on <html> through a $subscribe.
  3. Pagination store for a list: page, pageSize, getters for pageItems and pageCount, actions next/prev.
  4. Undo/redo plugin: a plugin that records $subscribe snapshots for any store with undoable: true.
  5. Migrate a small Vuex store you wrote earlier, using the checklist from the migration chapter.

Where to go from here

Return to the Pinia track page to revisit any lesson. If you are using Vue Router or building a Nuxt app, combine what you learned here with their guards and middleware, and keep the habit of writing a few store tests as you go.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which is the better way to model 'items' and 'how many items'?

    Minimal state plus derived getters cannot get out of sync.
  2. 2. What is wrong with const { count } = useCounterStore()?

    Destructuring state copies the value. Use storeToRefs(store) to keep a reactive link.
  3. 3. Which state should NOT go into a global store?

    Purely local UI state belongs in the component.
  4. 4. Why prefer one status string over loading and error booleans?

    Two booleans allow impossible combinations such as loading and error at once; one status value does not.

Summary

  • One store per domain concept; minimal state with derived getters.
  • Rules, validation and API calls live in actions; components stay thin.
  • Keep state serializable; model loading and errors with a single status.
  • Destructure with storeToRefs, patch instead of replacing, derive instead of copying.
  • Keep local state local; avoid cycles; reset and persist deliberately; test stores.

Next: Back to the Pinia track