← Back to all snippets
JAVASCRIPT

Global State Management with Pinia

Learn to manage global application state efficiently using Pinia, Vue 3's recommended state management library, with actions, getters, and reactive state.

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

export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0,
    name: 'Vue Dev'
  }),
  getters: {
    doubleCount: (state) => state.count * 2,
    greetUser: (state) => `Hello, ${state.name}!`
  },
  actions: {
    increment() {
      this.count++;
    },
    incrementBy(amount) {
      this.count += amount;
    }
  }
});

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

const app = createApp(App);
app.use(createPinia());
app.mount('#app');

// src/components/CounterDisplay.vue
<template>
  <div>
    <h1>Counter: {{ counterStore.count }}</h1>
    <p>Double Count: {{ counterStore.doubleCount }}</p>
    <p>{{ counterStore.greetUser }}</p>
    <button @click="counterStore.increment()">Increment</button>
    <button @click="counterStore.incrementBy(5)">Increment by 5</button>
  </div>
</template>

<script setup>
import { useCounterStore } from '../stores/counter';

const counterStore = useCounterStore();
</script>
How it works: Pinia is the official state management library for Vue.js, offering a simple and intuitive API. This snippet demonstrates how to define a store with reactive `state`, `getters` for derived state, and `actions` for modifying the state. It then shows how to install Pinia globally in `main.js` and how to consume the store within a component using `useCounterStore()` to access and update shared application state.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs