Vue Pinia (State Management)

Modern state management for Vue applications

🍍 What is Pinia?

Pinia is the official state management library for Vue 3. It provides a simple, intuitive API for managing shared state across components with TypeScript support and excellent developer experience.


// Basic Pinia store example
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
  state: () => ({ count: 0 }),
  actions: {
    increment() {
      this.count++
    }
  }
})
                                    

Key Pinia Concepts

📦

Stores

Central place to hold state

const useStore = defineStore('main', {
  state: () => ({ user: null })
})
🎯

Actions

Methods to modify state

actions: {
  setUser(user) {
    this.user = user
  }
}
🔍

Getters

Computed values from state

getters: {
  doubleCount: (state) => 
    state.count * 2
}

Reactivity

Automatic UI updates

const store = useStore()
// Changes update automatically
store.count++

🔹 Creating Your First Store

Define a store with state, getters, and actions:

// stores/user.js
import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    name: 'Guest',
    isLoggedIn: false
  }),
  
  getters: {
    greeting: (state) => `Hello, ${state.name}!`
  },
  
  actions: {
    login(username) {
      this.name = username
      this.isLoggedIn = true
    },
    logout() {
      this.name = 'Guest'
      this.isLoggedIn = false
    }
  }
})

🔹 Using Store in Components

Access and modify store state in your Vue components:

<script setup>
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()

function handleLogin() {
  userStore.login('John Doe')
}
</script>

<template>
  <div>
    <h2>{{ userStore.greeting }}</h2>
    <p>Status: {{ userStore.isLoggedIn ? 'Logged In' : 'Guest' }}</p>
    <button @click="handleLogin">Login</button>
    <button @click="userStore.logout()">Logout</button>
  </div>
</template>

🔹 Setup Syntax Alternative

Use the Composition API style for more flexibility:

// stores/counter.js
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', () => {
  // State
  const count = ref(0)
  
  // Getters
  const doubleCount = computed(() => count.value * 2)
  
  // Actions
  function increment() {
    count.value++
  }
  
  return { count, doubleCount, increment }
})

🔹 Installation & Setup

Get started with Pinia in your Vue project:

Installation Steps:

  1. Install Pinia: npm install pinia
  2. Create Pinia instance in main.js
  3. Create your stores
  4. Use stores in components
// main.js
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'

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

app.use(pinia)
app.mount('#app')

🧠 Test Your Knowledge

What function is used to create a Pinia store?