Thuta Learning
AdvancedWeb Developmentbeginner

State Management with Pinia

Relax. We'll talk through this in plain words — no textbook voice.

What you'll walk away with

  • Build a Pinia store
  • Separate state, getters, and actions
  • Use a store inside a component

Let's break it down simply

Don't rush to move local component state elsewhere. Reach for Pinia when state is shared across multiple components — things like user sessions, a cart, or app-wide filters. Declare state as a function, write derived state as getters, and write changes as actions.

javascript
import { defineStore } from 'pinia'

export const useCartStore = defineStore('cart', {
  state: () => ({ items: [] }),
  getters: {
    totalItems: (state) => state.items.length
  },
  actions: {
    add(product) {
      this.items.push(product)
    }
  }
})
You should see
cart.totalItems = 0

Try it yourself

Build a Pinia store with theme and locale state for user preferences.

Pinia StatePinia

Easy traps

  • Not registering the Pinia plugin on the app
  • Dumping every bit of component-local state into a global store

Exercise

Build a Pinia store with theme and locale state for user preferences.

You'll know it worked when: cart.totalItems = 0

State Management with Pinia | Thuta Learning