๐Ÿ”„ State Management with Pinia and Vue.js (Composition API) Lifecycle Hooks ๐Ÿš€

Dharmendra Kumar - Sep 12 - - Dev Community

With the rise of the Composition API in Vue 3, Pinia has emerged as a lighter, simpler, and more modern state management library compared to Vuex. Pinia integrates seamlessly with the Composition API, offering a more intuitive way to manage global state. In this post, we'll build a simple counter app using Pinia and Vue.js lifecycle hooks to demonstrate how you can manage state globally and control component behavior during its lifecycle.


๐ŸŒ What is Pinia?

Pinia is the state management library designed for Vue 3. It acts as a store that can hold state globally, similar to Vuex, but with a simpler API and better integration with the Composition API.


๐Ÿ› ๏ธ Building a Simple Counter App with Pinia

Let's build a basic counter app using Pinia to manage the counter's state globally. We'll use Vue.js lifecycle hooks to interact with the state as the component is created and updated.


Step 1: Setting up the Pinia Store (store/counterStore.js)

First, we'll define our Pinia store that manages the counter state.

// store/counterStore.js
import { defineStore } from 'pinia';

export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0,  // The initial counter value
  }),
  actions: {
    increment() {
      this.count++;
    },
  },
});
Enter fullscreen mode Exit fullscreen mode
  • state: Stores the initial value of the counter.
  • actions: The increment function updates the counter value.

Step 2: Using Pinia in the Vue Component with Composition API

Now, let's create a Vue component that interacts with the Pinia store using the Composition API and Vue.js lifecycle hooks.

Counter Component (Counter.vue)
<template>
  <div>
    <h1>Global Counter: {{ counterStore.count }}</h1>
    <button @click="counterStore.increment">Increment</button>
  </div>
</template>

<script setup>
import { onMounted, watch } from 'vue';
import { useCounterStore } from './store/counterStore';

// Using the Pinia store
const counterStore = useCounterStore();

// Lifecycle hook: called when the component is mounted
onMounted(() => {
  console.log('Component mounted! Initial count:', counterStore.count);
});

// Watch for changes to the count
watch(() => counterStore.count, (newCount) => {
  console.log('Count updated! New count:', newCount);
});
</script>
Enter fullscreen mode Exit fullscreen mode
Explanation:
  1. Pinia Store (useCounterStore): The useCounterStore function gives us access to the counter's state and actions.
  2. onMounted: Logs the initial counter value when the component is mounted (lifecycle hook equivalent to mounted).
  3. watch: Watches for changes in counterStore.count and logs the updated count every time it changes.

Step 3: Registering Pinia in Your Vue App

We need to register Pinia in the main application file to make it available globally to all components.

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);  // Use Pinia for state management
app.mount('#app');
Enter fullscreen mode Exit fullscreen mode

๐ŸŒŸ Vue.js Lifecycle Hooks + Pinia: Practical Example

In the above example, we use Pinia for global state management and lifecycle hooks to interact with the component during key stages.

  1. onMounted: This Composition API hook runs once the component is mounted, similar to the mounted lifecycle hook in the Options API. Itโ€™s a good place to initialize or log the componentโ€™s state.
  2. watch: We use watch to monitor the counter state and react to changes. Every time counterStore.count updates, the new value is logged to the console.

๐Ÿ“Š Key Differences Between Pinia and Vuex

  • Simpler API: Pinia has a more straightforward and flexible API, making it easier to manage global state.
  • Composition API: Pinia is fully integrated with the Composition API, whereas Vuex is more suited for the Options API.
  • Lightweight: Pinia is a smaller, faster, and more lightweight state management solution, ideal for modern Vue 3 applications.

๐Ÿง  Key Takeaways

  • Pinia provides a simpler and more modern way to manage global state in Vue 3 applications.
  • The Composition API combined with lifecycle hooks like onMounted and watch allows you to create highly modular, flexible components.
  • Pinia integrates seamlessly into Vue 3, making state management easier and more intuitive than ever.

By using Pinia and Vue.js lifecycle hooks, you can efficiently manage global state while keeping your components clean and maintainable. This approach is perfect for modern Vue 3 applications that rely on the Composition API for flexibility and scalability!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player