This content originally appeared on DEV Community and was authored by Dharmendra Kumar
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++;
},
},
});
- 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>
Explanation:
-
Pinia Store (
useCounterStore
): TheuseCounterStore
function gives us access to the counter's state and actions. -
onMounted: Logs the initial counter value when the component is mounted (lifecycle hook equivalent to
mounted
). -
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');
๐ 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.
-
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. -
watch: We use
watch
to monitor the counter state and react to changes. Every timecounterStore.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
andwatch
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!
This content originally appeared on DEV Community and was authored by Dharmendra Kumar
Dharmendra Kumar | Sciencx (2024-09-12T10:22:23+00:00) ๐ State Management with Pinia and Vue.js (Composition API) Lifecycle Hooks ๐. Retrieved from https://www.scien.cx/2024/09/12/%f0%9f%94%84-state-management-with-pinia-and-vue-js-composition-api-lifecycle-hooks-%f0%9f%9a%80/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.