Pinia is the officially recommended state management solution for Vue.js. Nuxt 3 is the awesome meta framework built on top of Vue that includes out of the box support for SSR and a huge number of time-saving conventions. In this article, let’s take a look at how and why to use them together for the perfect global state management.
Yes, Nuxt does provide the useState
composable as part of it’s core package for managing global state. You can read more about using useState for global state management in Nuxt docs. However, it’s still advisable to consider installing Pinia for a few reasons:
useState
Ok, so you want to use Pinia with Nuxt as your global state management solution? Sweet! How do you do it?
First, in order to use Pinia with Nuxt, you can install the official @pinia/nuxt
module.
npx nuxi@latest module add pinia
Then you’ll need to register the module in nuxt.config.ts
.
// nuxt.config.ts
export default defineNuxtConfig({
modules: ['@pinia/nuxt'],
});
After that you should be ready to start creating and using your first Pinia store! (If you aren’t familiar with the basics of Pinia, checkout our popular course on the topic!)
By default, @pinia/nuxt
provides several convenient auto-imports to streamline your development process:
usePinia()
: Works similarly to getActivePinia()
but is optimized for Nuxt.defineStore()
: For defining your Pinia stores.storeToRefs()
: Extract individual refs from a store when needed.acceptHMRUpdate()
: Enables hot module replacement (HMR) for your stores.This means you no longer have to manually import these from pinia whenever your defining your stores.
// stores/CountStore.ts
// no need to import defineStore and acceptHMRUpdate
export const useCountStore = defineStore('CountStore', {
//...
});
if (import.meta.hot) {
import.meta.hot.accept(acceptHMRUpdate(useCountStore, import.meta.hot));
}
Additionally, all stores within your stores
folder are automatically imported. However, nested stores are not automatically detected. You can adjust this behavior by customizing the storesDirs
option:
// nuxt.config.ts
export default defineNuxtConfig({
// Other configurations
modules: ['@pinia/nuxt'],
pinia: {
storesDirs: ['./stores/**', './custom-folder/stores/**'],
},
})
Checkout this stackbliz project to see a demo of Nuxt + Pinia in action. While you’re at it, if you’d like to learn more about Nuxt 3 then checkout the upcoming Mastering Nuxt 3 course. Or if you’d like to dive deeper into Pinia for both basics and more advanced topics checkout our course: Pinia, the Enjoyable Vue Store.
Our goal is to be the number one source of Vue.js knowledge for all skill levels. We offer the knowledge of our industry leaders through awesome video courses for a ridiculously low price.
More than 200.000 users have already joined us. You are welcome too!
© All rights reserved. Made with ❤️ by BitterBrains, Inc.