Tutorials Logic, IN info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Website Development
Practice
Quiz Challenge Interview Questions Certification Practice
Tools
Online Compiler JSON Formatter Regex Tester CSS Unit Converter Color Picker
Compiler Tools

Pinia Vue State Management: Tutorial, Examples, FAQs & Interview Tips

What is Pinia?

Pinia is the official state management library for Vue 3. It replaces Vuex with a simpler, more intuitive API. Pinia stores are like components without a template - they hold reactive state that any component can access.

  • State - reactive data (like data() in components)
  • Getters - computed values derived from state
  • Actions - methods that modify state (can be async)
Pinia - Store Definition and Usage
// stores/counter.js
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

// Setup store (Composition API style - recommended)
export const useCounterStore = defineStore('counter', () => {
    // State
    const count = ref(0)
    const history = ref([])

    // Getters (computed)
    const doubleCount = computed(() => count.value * 2)
    const isPositive  = computed(() => count.value > 0)

    // Actions
    function increment() {
        count.value++
        history.value.push(`+1 -> ${count.value}`)
    }

    function decrement() {
        count.value--
        history.value.push(`-1 -> ${count.value}`)
    }

    function reset() {
        count.value = 0
        history.value = []
    }

    function incrementBy(amount) {
        count.value += amount
    }

    return { count, history, doubleCount, isPositive, increment, decrement, reset, incrementBy }
})

// Options store (Options API style)
export const useCounterOptionsStore = defineStore('counterOptions', {
    state: () => ({ count: 0 }),
    getters: {
        double: (state) => state.count * 2
    },
    actions: {
        increment() { this.count++ },
        async fetchCount() {
            const res = await fetch('/api/count')
            this.count = await res.json()
        }
    }
})
// stores/auth.js
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useAuthStore = defineStore('auth', () => {
    const user = ref(null)
    const token = ref(localStorage.getItem('token'))
    const loading = ref(false)

    const isLoggedIn = computed(() => !!token.value)
    const userName   = computed(() => user.value?.name || 'Guest')

    async function login(email, password) {
        loading.value = true
        try {
            const res = await fetch('/api/login', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ email, password })
            })
            const data = await res.json()
            user.value  = data.user
            token.value = data.token
            localStorage.setItem('token', data.token)
        } finally {
            loading.value = false
        }
    }

    function logout() {
        user.value  = null
        token.value = null
        localStorage.removeItem('token')
    }

    return { user, token, loading, isLoggedIn, userName, login, logout }
})
<template>
  <div>
    <!-- Counter store -->
    <p>Count: {{ counter.count }}</p>
    <p>Double: {{ counter.doubleCount }}</p>
    <button @click="counter.increment()">+1</button>
    <button @click="counter.decrement()">-1</button>
    <button @click="counter.reset()">Reset</button>

    <!-- Auth store -->
    <p v-if="auth.isLoggedIn">Hello, {{ auth.userName }}!</p>
    <button v-if="!auth.isLoggedIn" @click="auth.login('alice@example.com', 'password')">
      Login
    </button>
    <button v-else @click="auth.logout()">Logout</button>
  </div>
</template>

<script setup>
import { useCounterStore } from '@/stores/counter'
import { useAuthStore } from '@/stores/auth'

// Use stores - reactive, auto-updates template
const counter = useCounterStore()
const auth    = useAuthStore()

// Destructure with storeToRefs (preserves reactivity)
import { storeToRefs } from 'pinia'
const { count, doubleCount } = storeToRefs(counter)
// Actions can be destructured directly (not reactive)
const { increment, reset } = counter
</script>

Deep Dive: Pinia in Real Projects

Understanding Pinia is not just about syntax. In production applications, this topic directly affects maintainability, debugging speed, and team collaboration. Focus on readability, small reusable patterns, and predictable state flow when implementing Pinia.

A practical approach is to first implement the simplest working version, then refactor into reusable pieces (components/composables/stores) only when duplication appears. This helps keep your Vue codebase clean while avoiding over-engineering.

Common Mistakes to Avoid

  • Mixing too many responsibilities in one component instead of separating logic by concern.
  • Skipping meaningful naming for variables, emits, and component props.
  • Ignoring edge cases like empty data, loading states, and error handling.
  • Optimizing too early before measuring real bottlenecks in browser devtools.
  • Not creating small test scenarios to validate behavior after each change.

Mini Practice Checklist

  1. Build a small demo focused only on Pinia.
  2. Add one edge case (empty/loading/error) and handle it cleanly.
  3. Refactor repeated logic into a reusable function/composable.
  4. Add clear comments only where logic is non-obvious.
  5. Verify behavior with manual testing and Vue Devtools.
Key Takeaways
  • This chapter on Pinia focuses on practical Vue 3 patterns used in real projects.
  • Prefer the Composition API with script setup for cleaner and more scalable component logic.
  • Keep components focused and move reusable logic into composables when complexity grows.
  • Use Vue Devtools to inspect component state, props, emits, and performance during development.
  • Write small experiments for each concept before applying it in production code.
  • After finishing this chapter, continue to the next related topic in the Vue roadmap.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.