FrontEND/vue

Vue 3에서 Pinia 상태관리 적용 가이드

mingmingIT 2025. 4. 23. 10:06

Vuex보다 가볍고, 타입 지원도 뛰어난 Vue 3 공식 상태관리 라이브러리 Pinia.
이번 포스팅에서는 Pinia를 설치하고 기본적인 상태관리 로직을 구현하는 방법을 소개합니다.


1. Pinia 설치

터미널에서 다음 명령어를 입력하여 설치합니다.

npm install pinia

그리고 main.js 또는 main.ts에서 Pinia를 등록합니다.

// src/main.js
import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia'

const app = createApp(App)
const pinia = createPinia()

app.use(pinia)
app.mount('#app')

2. 상태 저장소(Store) 만들기

Pinia는 Composition API 스타일로 구성됩니다. 예를 들어, 카운터 상태를 관리하는 store를 만들어 보겠습니다.

// src/stores/useCounterStore.js
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0
  }),
  actions: {
    increment() {
      this.count++
    },
    decrement() {
      this.count--
    }
  },
  getters: {
    doubleCount: (state) => state.count * 2
  }
})

여기서 state는 상태값을 정의하고, actions는 메서드, getters는 계산된 속성을 정의합니다.
defineStore는 첫 번째 인자로 식별자(id)를, 두 번째 인자로 설정 객체를 받습니다.


3. 컴포넌트에서 사용하기

이제 위에서 만든 상태 저장소를 컴포넌트에서 사용할 수 있습니다.

<!-- src/views/CounterView.vue -->
<script setup>
import { useCounterStore } from '../stores/useCounterStore'

const counter = useCounterStore()
</script>

<template>
  <div class="p-4">
    <h1 class="text-xl font-bold">🧮 Count: {{ counter.count }}</h1>
    <p>두 배 값: {{ counter.doubleCount }}</p>

    <div class="space-x-2 mt-4">
      <button @click="counter.increment" class="bg-blue-500 text-white px-4 py-1 rounded">+1</button>
      <button @click="counter.decrement" class="bg-red-500 text-white px-4 py-1 rounded">-1</button>
    </div>
  </div>
</template>

Pinia의 상태는 자동으로 반응형(Reactive)이며, actions와 getters도 마치 컴포넌트의 메서드처럼 사용할 수 있습니다.


4. 추가 팁

상태 변경 감지하기

import { watch } from 'vue'

watch(() => counter.count, (newVal) => {
  console.log('count changed:', newVal)
})

다른 컴포넌트에서도 동일한 상태 공유 가능

const counter = useCounterStore()
// 동일한 인스턴스를 사용하므로 전역 상태처럼 동작

✅ 요약

항목 설명
설치 npm install pinia
등록 main.js에서 app.use(pinia)
정의 defineStore()로 Store 생성
사용 useStore()로 가져와서 사용
특징 반응형, TypeScript 친화, Composition API 기반

마무리

Vue 3에서는 더 이상 Vuex를 고집할 필요가 없습니다.
Pinia는 단순하면서도 강력한 기능을 제공하며, 작은 프로젝트부터 대규모 앱까지 유연하게 적용 가능합니다.