Intermediate LevelVue JS
Why did Pinia replace Vuex and how do you structure a Pinia store?
❓ Interview Prompt: Explain Pinia advantages over Vuex (no mutations, TypeScript support, modular stores) and Setup vs Option store syntax.
Pinia is the official state management library for Vue 3, replacing the legacy Vuex library.
Why Pinia Replaced Vuex:
1
No More Mutations: Vuex required verbose 'actions' (async) that committed 'mutations' (sync) to modify state. Pinia eliminates mutations entirely — actions can be synchronous or asynchronous and mutate state directly.
2
Flawless TypeScript Support: Pinia is built with TypeScript from the ground up, providing instant autocompletion without custom wrappers.
3
No Nested Modules: Instead of a single giant Vuex store with nested modules, Pinia uses independent, modular stores imported only where needed.
Setup Stores vs Option Stores:
Pinia supports two syntaxes: Option Stores ('state', 'getters', 'actions') and Setup Stores (using Composition API 'ref' for state, 'computed' for getters, and functions for actions).
Code Implementation Example
javascript
// stores/userStore.js — Pinia Setup Store Syntax
import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
export const useUserStore = defineStore('user', () => {
// STATE (ref)
const user = ref(null);
const token = ref(localStorage.getItem('token') || '');
// GETTERS (computed)
const isAuthenticated = computed(() => !!token.value);
// ACTIONS (functions mutating state directly!)
async function login(email, password) {
const res = await fetch('/api/login', { method: 'POST', body: JSON.stringify({ email, password }) });
const data = await res.json();
token.value = data.token;
user.value = data.user;
}
return { user, token, isAuthenticated, login };
});💡Pinia Setup Store using ref for state, computed for getters, and functions for actions.
🎯 Interview Key Takeaway
Pinia removes Vuex mutations, provides native TypeScript inference, and uses modular Setup stores.
#Pinia#Vuex#State Management#Intermediate
Back to all Vue JS Questions→