← Back to Tutorials

Pinia State Management

Replace Vuex with Pinia. Stores, actions, getters, and TypeScript integration.

Why Pinia?

Pinia is the official state management library for Vue 3. It's simpler than Vuex, has excellent TypeScript support, and works great with Composition API.

Pinia uses a store-based architecture that feels natural with Vue's reactivity system. Stores are defined once and reused across your app.

Creating a Store

Stores contain three main parts: state (reactive data), getters (computed values), and actions (methods).

import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    user: null,
    isAuthenticated: false
  }),
  actions: {
    login(credentials) {
      // login logic
    }
  },
  getters: {
    fullName: (state) => state.user?.name
  }
})

Using the Store

Access stores anywhere in your app with the useStore() composable.

const userStore = useUserStore()
userStore.login({ email, password })
console.log(userStore.fullName)

Composition API Style

You can also define stores using the Composition API style with setup() function.

export const useCartStore = defineStore('cart', () => {
  const items = ref([])
  const total = computed(() => items.value.reduce((sum, item) => sum + item.price, 0))
  
  function addItem(item) {
    items.value.push(item)
  }
  
  return { items, total, addItem }
})

Key takeaways

  • Pinia is simpler and more type-safe than Vuex
  • Stores are defined with defineStore()
  • State, actions, and getters in one place
  • Works seamlessly with Composition API
  • Supports both options API and setup syntax
  • Excellent TypeScript support with proper inference