Learn Vue.js · 10/13

Global State Management: Pinia

8 min read

1. Why Do We Need Global State? (The Modern Standard)

Definition:
Global state refers to application data that is stored outside of the component tree and can be accessed, read, or modified by multiple unrelated components.

The Problem:
In a standard Vue application, data flows in one direction: downwards from parent components to child components via props, and upwards via emits (events). If two sibling components, or components deeply nested in entirely different parts of your application, need to share the same data (like user authentication details or a shopping cart), you are forced to pass that data up and down the component tree. This process is called "prop drilling," and it is incredibly tedious, hard to maintain, and prone to bugs.

The Solution:
We extract the shared data from the components and place it in a centralized, reactive location called a "Store." Any component can directly connect to this store to read data or trigger updates, completely bypassing the component hierarchy.

What is Pinia?
Pinia is the official state management library for Vue 3. It replaced Vuex as the modern standard. Pinia is extremely lightweight (around 1.5kb), offers first-class TypeScript support, and natively utilizes Vue 3's Composition API under the hood.

Fun Fact: Vuex is currently enjoying a well-deserved retirement on a digital beach. "Pinia" is the closest English pronunciation of "piña" (Spanish for pineapple). A pineapple is actually a cluster of individual flowers that join together to create a single fruit. Similarly, Pinia allows you to create multiple independent stores that seamlessly wire together to form your application's state.

The Restaurant Flow:
Imagine you are running a busy restaurant. You have waiters (Vue components) and customers (users). If every waiter had to physically walk up to every other waiter to ask, "Hey, did table 5 get their drinks?" or "Is the kitchen out of cheese?", the restaurant would descend into chaos. This is prop drilling.

Instead, you install a central digital order board in the kitchen (the Store). Any waiter can look at the board to see the status of any table (Reading State). Any waiter can press a button on the board to mark an order as complete (Triggering Actions). The board instantly updates for everyone (Reactivity).


2. Defining and Registering a Pinia Store

Before we can use a store, we need to install the library and attach it to our Vue application.

The Problem:
Vue components only know about their own internal logic by default. For a store to be accessible application-wide, Vue needs an injection mechanism at the very root of the application.

The Solution:
We install Pinia and register it as a plugin in the main application instance.

Installation

Strictly following the latest standard, install Pinia via your package manager:

bash
npm install pinia

Registration

Navigate to your main.js or main.ts file. We need to import createPinia, instantiate it, and tell our Vue app to use it.

javascript
// src/main.js
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'

const pinia = createPinia()
const app = createApp(App)

// Injecting the global state manager into the app
app.use(pinia)
app.mount('#app')

Defining a Store

A store is created using the defineStore function. In industry practice, stores are organized inside a src/stores directory. Each store manages a specific domain of your application (e.g., userStore, cartStore, productStore).

javascript
// src/stores/cart.js
import { defineStore } from 'pinia'

// The first argument ('cart') is a unique ID for the store.
// Pinia uses this ID to connect the store to the Vue DevTools.
export const useCartStore = defineStore('cart', {
  // We will define our state, getters, and actions here
})

Note on naming conventions: It is an industry standard to name the returned function starting with use and ending with Store (e.g., useCartStore).


3. Managing State, Getters, and Actions

A Pinia Options Store is composed of three core concepts. If you understand standard Vue components, you already understand Pinia.

  • State = data
  • Getters = computed properties
  • Actions = methods

State

Definition:
State is a function that returns an object containing the central data repository for the store.

Why a function?
If state were a simple object, the data could leak and be shared across different user sessions during Server-Side Rendering (SSR). Returning a fresh object from a function guarantees every instance gets its own isolated data.

javascript
export const useCartStore = defineStore('cart', {
  state: () => ({
    items: [],
    discountCode: null,
    taxRate: 0.08
  })
})

Getters

Definition:
Getters are computed properties derived directly from the store's state.

The Problem:
If you need to calculate the total price of items in the cart, writing that calculation directly inside a component means you have to duplicate that logic if another component needs the total price.

The Solution:
Define the calculation once in a getter. Under the hood, Pinia uses Vue's computed() reactivity, meaning getters cache their results and only recalculate when the underlying state changes.

javascript
export const useCartStore = defineStore('cart', {
  state: () => ({
    items: [{ name: 'Pizza', price: 15 }, { name: 'Soda', price: 3 }],
  }),
  getters: {
    // The state is passed as the first argument
    totalItems: (state) => state.items.length,
    
    // You can also use 'this' to access other getters, but you must define a standard function (no arrow functions)
    totalPrice(state) {
      const subtotal = state.items.reduce((total, item) => total + item.price, 0)
      return subtotal + (subtotal * this.taxRate)
    }
  }
})

Actions

Definition:
Actions are functions that contain business logic and modify the state.

The Problem:
If components modify the global state randomly, it becomes impossible to track where data changes are coming from.

The Solution:
We encapsulate the logic for changing state inside Actions. Any component can call these actions.

javascript
export const useCartStore = defineStore('cart', {
  state: () => ({ items: [] }),
  actions: {
    addItem(newItem) {
      // 'this' refers to the store instance
      this.items.push(newItem)
    },
    clearCart() {
      this.items = []
    }
  }
})

⚠️ Industry Standard Trap: The Reactivity Loss

When you use the store in a component, you might be tempted to destructure it like a normal JavaScript object. Do not do this.

html
<script setup>
import { useCartStore } from '@/stores/cart'
// ❌ BAD: This breaks Vue's reactivity. 'items' will not update in the template!
const { items } = useCartStore() 
</script>

The Solution: Use Pinia's storeToRefs utility. This extracts state and getters while keeping them reactive. Actions can be destructured normally because functions do not require reactivity.

html
<script setup>
import { useCartStore } from '@/stores/cart'
import { storeToRefs } from 'pinia'

const cartStore = useCartStore()

// ✅ GOOD: State and Getters remain reactive
const { items, totalPrice } = storeToRefs(cartStore)

// ✅ GOOD: Actions can be destructured directly
const { addItem } = cartStore
</script>

4. Mutating State and Handling Async Actions

Mutating State Directly vs $patch

Definition:
Mutation refers to the act of changing the values within your state object.

The Problem:
Sometimes you need to update multiple pieces of state simultaneously. Changing them one by one (store.a = 1, store.b = 2) triggers Vue's reactivity system multiple times, causing unnecessary performance overhead.

The Solution:
Pinia allows you to mutate state directly in your components or actions. However, for batch updates, Pinia provides the $patch method, which applies multiple changes at the exact same time, triggering the UI to re-render only once.

javascript
import { useCartStore } from '@/stores/cart'

const cartStore = useCartStore()

// Direct mutation (Good for single updates)
cartStore.discountCode = 'SUMMER2026'

// $patch mutation (Industry standard for multiple simultaneous updates)
cartStore.$patch({
  discountCode: 'WINTER2026',
  taxRate: 0.05,
  items: []
})

Handling Async Actions

Definition:
Asynchronous actions are methods that pause their execution to wait for a background task (like an API request to a database) to finish before continuing.

The Problem:
In the older Vuex library, you were forced to separate synchronous updates (mutations) and asynchronous updates (actions), resulting in massive amounts of boilerplate code.

The Solution:
Pinia actions fully support JavaScript's async/await syntax. You write your API calls directly inside the action, await the data, and assign it straight to this.state.

javascript
export const useProductStore = defineStore('product', {
  state: () => ({
    products: [],
    isLoading: false,
    error: null
  }),
  actions: {
    async fetchProducts() {
      this.isLoading = true
      this.error = null
      
      try {
        // Pauses execution until the server responds
        const response = await fetch('https://api.my-store.com/products')
        if (!response.ok) throw new Error('Network response failed')
        
        const data = await response.json()
        
        // Mutates state directly with the fetched data
        this.products = data
      } catch (err) {
        this.error = err.message
      } finally {
        this.isLoading = false
      }
    }
  }
})

The Bank Flow:
You are the cashier (Component). You press the "Process Payment" button (Action). The system sends a request to the bank and waits (await fetch()). While waiting, the terminal displays "Loading..." (state.isLoading = true). Once the bank approves the transaction, the system directly updates the cash drawer (this.products = data) and prints the receipt.


References & Extra Reading

Challenge

You are tasked with creating a Pinia store to manage a user's profile data. The store should handle fetching data asynchronously, provide derived state, and allow for batched state updates.

Your Tasks:

  1. Complete the Pinia store definition with the unique ID 'user'.
  2. State: The store's state must be a function that returns an object with the following properties:
    • profile: An object to hold user data (e.g., id, name, email), initialized to null.
    • isLoading: A boolean to track the loading state, initialized to false.
    • lastUpdated: A Date object, initialized to null.
  3. Getters: Create a getter named userInitials. If state.profile.name exists, it should return the initials (e.g., "Jane Doe" -> "JD"). If not, it should return an empty string.
  4. Actions:
    • Implement an action named updateName. This action must accept a newName string. Use the $patch method to update both the profile.name and the lastUpdated state properties in a single operation. The lastUpdated property should be set to the current Date.
    • Implement an async action named fetchUserProfile. This action must accept a userId.
      • Immediately set isLoading to true.
      • Use the provided fetchUserDataFromApi(userId) function to simulate fetching data.
      • After the data is fetched, update the profile state with the result.
      • Finally, set isLoading back to false.

Expected result

Your code should be a complete and valid Pinia store definition that fulfills all the requirements specified in the instructions.

Correct Implementation Checklist:

  • State:
    • The state property is a function (() => ({...})).
    • It returns an object containing profile: null, isLoading: false, and lastUpdated: null.
  • Getters:
    • The getters object contains a key userInitials.
    • The userInitials getter correctly handles the case where this.profile or this.profile.name is null/undefined.
    • It correctly extracts and combines the first letter of the first and last name.
  • Actions:
    • The actions object contains an updateName(newName) method.
    • This method correctly uses this.$patch to update this.profile.name and this.lastUpdated with new Date().
    • The actions object contains an async fetchUserProfile(userId) method.
    • This method correctly sets this.isLoading = true at the beginning and this.isLoading = false at the end.
    • It properly awaits the fetchUserDataFromApi call and assigns the result to this.profile.
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.