Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 87 ยท State Management

Building a Simple Store

Build a small Vue 3 store from reactive state, computed getters and action functions. Expose it read-only, share it across components and learn when a factory beats a singleton.

In the previous lesson you saw that two components can share data when they import the same reactive object. That works, but as soon as five components change the same state in five different ways, bugs become hard to trace: who set total to a negative number? A store adds a little discipline on top of shared state. It keeps the state, the values derived from it and the functions that change it together in one place, and it lets everyone else only read.

You do not need a library to build one. Vue's reactivity API already has everything: reactive for state, computed for derived values, plain functions for actions and readonly to protect the state from outside writes. In this lesson you will build a shopping-cart store this way. The same ideas are what Pinia packages up with extra tooling.

The anatomy of a store

A store has three kinds of members:

  • State: the source of truth, a reactive object (or some refs).
  • Getters: values computed from state. In a store module they are simply computed refs, cached until the state they read changes.
  • Actions: functions that change the state. Every change goes through one of them, so the rules live in one place.

The module creates the state once, at the top level, and exports a function that hands it out. Because ES modules are evaluated only once, every component that imports the module receives the same state. That is why a plain module can act as a singleton.

flowchart LR
    C["Component<br/>(click)"] -->|"calls"| A["Action<br/>addItem()"]
    A -->|"mutates"| S["State<br/>reactive object"]
    S -->|"derives"| G["Getters<br/>computed()"]
    S -->|"read-only view"| C
    G -->|"read"| C

Components never write to the state directly: they call actions, and read state and getters.

A cart store you can run

The example below keeps a cart in one store and uses it from two different components, a product list and a cart summary. Neither component knows about the other. Prices are stored in cents so that the arithmetic stays exact.

A cart store shared by two components

Click a few products: the count and total in the summary change although the product list never mentions them. Both components call useCart(), which returns the same itemCount and total computed refs every time. Destructuring them in setup() is safe because they are refs (see reactive objects for why destructuring plain state is not).

Notice the useCart() function. It is the only door into the store, so it decides what is exposed. The state goes out wrapped in readonly, the getters are computed refs (which are already read-only), and the actions go out as they are.

The example loads the full Vue build (vue.esm-browser.prod.js) because it compiles the template strings in the browser. In a real project with a build tool and .vue files, templates are compiled ahead of time and you import from "vue".

Why expose the state as read-only

Without readonly, any component could write state.items = [] or change a price in the middle of an unrelated handler. The store would still work, but you would lose the main benefit: knowing that every change goes through an action. readonly(state) returns a proxy that can be read (and tracked) like the original, while every write is rejected.

Actions enforce the rules, readonly blocks the rest

Try "Buy 3" twice. The action refuses the second purchase because the rule (never sell more than the capacity) lives inside buy. Then press "Write directly". The component tries state.sold = 100, but it received the read-only view, so the write is ignored. This page loads the production build of Vue, which ignores the write silently; the development build prints a warning such as Set operation on key "sold" failed: target is readonly, which is your signal during development that a component skipped the action.

Using the store from an SFC

In a project with a build step, the store lives in its own file and components import it. This is read-only code, because the site's runner does not compile .vue files:

JavaScript
// stores/cart.js
import { reactive, computed, readonly } from "vue";

const state = reactive({ items: [] });
const total = computed(() =>
  state.items.reduce((sum, item) => sum + item.qty * item.cents, 0)
);

function addItem(name, cents) {
  const existing = state.items.find((item) => item.name === name);
  if (existing) existing.qty++;
  else state.items.push({ name, cents, qty: 1 });
}

export function useCart() {
  return { state: readonly(state), total, addItem };
}
VUE
<script setup>
import { useCart } from "./stores/cart.js";

const { state, total, addItem } = useCart();
</script>

<template>
  <button @click="addItem('Pen', 199)">Add pen</button>
  <p>{{ state.items.length }} lines, {{ total }} cents</p>
</template>

Inside a <script setup> template, top-level refs such as total are unwrapped automatically, and state is already reactive, so the template reads naturally.

Singleton or factory?

A module-level state is created once per JavaScript process. In the browser that means once per page, which is exactly what you want for a cart. There are two situations where it hurts:

  • Tests. State from one test leaks into the next. You would need a reset() action in every test.
  • Server-side rendering. One server process renders many users' requests. A module-level state would be shared by all of them, so one visitor's cart could end up in another visitor's HTML.

The fix is a factory: a function that creates a fresh store each time it is called.

JavaScript
export function createCartStore() {
  const state = reactive({ items: [] });
  const total = computed(() =>
    state.items.reduce((sum, item) => sum + item.qty * item.cents, 0)
  );
  function addItem(name, cents) { /* ... */ }
  return { state: readonly(state), total, addItem };
}

You then create one store per app (or per request) and hand it to components with provide and inject. This is the same trade-off that libraries solve for you: Pinia creates its stores inside an application-level object so every app (and every server request) gets its own.

Common pitfalls

  • Destructuring plain state. const { count } = state copies the current number and loses reactivity. Keep state.count, destructure refs only, or use toRefs.
  • Hiding side effects in getters. A getter should be a pure calculation. Put fetching and logging into actions.
  • Many tiny stores for one idea. Group state that changes together. Split a store when it has clearly separate responsibilities, such as cart versus user preferences.
  • Putting everything in the store. State used by only one component, such as whether a dropdown is open, belongs in that component. Share only what several parts of the page need.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why do all components that import a store module see the same state?

    A module runs once per page. The reactive object created at its top level is a single instance that every importer receives.
  2. 2. What does exposing the state with readonly() achieve?

    readonly returns a read-only proxy. Components can read it reactively, but writes are ignored (with a dev warning), so changes must go through actions, which hold the original state.
  3. 3. In a store module, which Vue API is the natural choice for a getter?

    A getter is a value derived from state that should be cached and updated automatically, which is exactly what computed provides.
  4. 4. Why might you prefer a createStore() factory over a module-level singleton?

    Module-level state lives as long as the process. Tests and server-side rendering need isolation, which a factory provides by creating new state each time.

Summary

  • A store groups state, getters and actions in one place so every change follows the same path.
  • Use reactive (or refs) for state, computed for getters and plain functions for actions.
  • Export a useX() function as the single entry point and return the state wrapped in readonly.
  • A module-level store is a singleton; use a factory plus provide/inject when you need isolation for tests or server rendering.
  • Keep local UI state local and share only what several components need.

Next: Pinia