State Management with Pinia
In a large application, you often need to store variables and make them available across multiple pages and components. These variables should be reactive, meaning that if the value changes in one place, it automatically updates everywhere it’s used. In Nuxt, the recommended way to manage global state is with Pinia.
Setting up Pinia
Install Pinia in your project:
npm install pinia
In Nuxt 4, you can enable Pinia by adding the official module in your
nuxt.config.ts:
export default defineNuxtConfig({
modules: [
'@pinia/nuxt',
],
})
Creating a Store
Create a new store inside the app/stores folder. For example:
// app/stores/useExampleStore.ts
import { defineStore } from 'pinia'
export const useExampleStore = defineStore('example', () => {
// state
const variable1 = ref(false)
// actions
function toggleVariable() {
variable1.value = !variable1.value
}
return {
variable1,
toggleVariable
}
})
This store can now be accessed globally from any page or component.
Using a Store in a Component
To use the store, import it and access its state or actions directly:
<script setup lang="ts">
import { useExampleStore } from '~/stores/useExampleStore'
const example = storeToRefs(useExampleStore())
function enableVariable() {
example.variable1 = true
}
</script>
<template>
<div>
<p>Variable value: {{ example.variable1 }}</p>
<button @click="enableVariable">Enable Variable</button>
</div>
</template>
Now, whenever variable1 changes in one component, the updated value will be reflected everywhere the store is used.
app/stores directory so Nuxt can automatically register them.