Vuex는 Vue.js에서 상태 관리를 위한 라이브러리로 오랫동안 사용되어 왔다.
Vuex가 5.x 버전을 앞둔 상태에서 Pinia가 등장하게 되고, Vue의 개발자인 Evan You는 pinia가 사실상 vuex5라고 언급했다.
그래서 Vue2에서는 Vuex를 써오다가 Vue3를 사용하면서는 상태 관리 라이브러리도 최신을 사용해보기 위해 Pinia를 사용해봤고(vue3의 공식적인 상태관리 도구가 pinia이기도 하다), 그 차이점을 정리해보려고 한다.
Pinia의 가장 큰 특징 중 하나는 mutation이 없다는 점이다.
기존의 vuex에서는 상태 변경을 위해 mutation으로 접근하였는데, pinia는 $patch로 상태를 변경하거나 actions에서 변경할 수 있다.
이는 개발자가 상태 관리를 보다 직관적이고 쉽게 할 수 있게 한다.
// Vuex
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++;
}
},
actions: {
increment({ commit }) {
commit('increment');
}
},
getters: {
count: state => state.count
}
});
export default store;
// Pinia
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0
}),
actions: {
increment() {
this.count++;
}
},
getters: {
doubleCount: (state) => state.count * 2
}
});
Vuex는 내부에 여러개의 모듈을 가질 수 있는 단일 store가 제공되었지만, Pinia에서는 필요한 컴포넌트에 바로 가져와서 사용할 수 있는 store를 여러 개 생성할 수 있다.
// Pinia
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0
}),
actions: {
increment() {
this.count++;
}
},
getters: {
doubleCount: (state) => state.count * 2
}
});
Vuex도 Composition API와 함께 사용할 수 있지만 설정이 다소 복잡할 수 있다.
하지만 Pinia는 Composition API와 자연스럽게 통합된다.
// Pinia
// js 파일
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import App from './App.vue';
const app = createApp(App);
const pinia = createPinia();
app.use(pinia);
app.mount('#app');
// vue 파일
<template>
<div>
<p>{{ count }}</p>
<button @click="increment">Increment</button>
<p>Double Count: {{ doubleCount }}</p>
</div>
</template>
<script>
import { useCounterStore } from './stores/counter';
export default {
setup() {
const counterStore = useCounterStore();
return {
count: counterStore.count,
increment: counterStore.increment,
doubleCount: counterStore.doubleCount
};
}
};
</script>
Vuex에서는 typescript를 쓰려면 다소 복잡하게 써야 했다.
하지만 Pinia는 그러한 문제점을 제거한 완전히 타입화된 상태 관리 라이브러리이다.
💡 Vuex를 사용하고 있는 대규모 프로젝트라면 안정성과 신뢰성이 검증된 Vuex를 계속 사용하는 것이 좋을 수 있다. 하지만, 새로 시작하는 Vue 3 프로젝트나 타입스크립트를 적극적으로 사용하고자 하는 경우에는 Pinia를 선택하는 것이 좋은 선택일 것 같다.