💚 Vue.js Intermediate

What is Pinia in depth?

Answer

Pinia (the official Vue state management library) has a simple, flat API: State: reactive data defined in state(). Access directly: store.count. Can be mutated directly in actions or from components (unlike Vuex mutations). Direct mutation: store.count++ (works but not recommended — use actions for traceability). $patch: efficiently update multiple state properties at once: store.$patch({ loading: false, users: newUsers }) or with a function for complex mutations: store.$patch((state) => { state.items.push(newItem); state.loading = false; });. $reset(): reset store to initial state (only in Options stores, not Setup stores). $subscribe(): watch store changes: store.$subscribe((mutation, state) => { localStorage.setItem("users", JSON.stringify(state.users)); });. $onAction(): track actions being called: store.$onAction(({ name, args, after, onError }) => { after(result => { /* log success */ }); onError(err => { /* log error */ }); });. Store composition: use other stores inside a store: const authStore = useAuthStore(); const { user } = storeToRefs(authStore);. Plugins: extend all stores with additional capabilities: pinia.use(({ store }) => { store.router = markRaw(router); });. Persistence plugin: pinia-plugin-persistedstate automatically persists store to localStorage. storeToRefs(): destructure store reactively: const { users, loading } = storeToRefs(store); — maintains reactivity (plain destructuring loses it).