State Management
🎯 Introduction
By the end of this article, you will be able to manage shared state in Nuxt. You will learn how to use useState, when to choose it over Pinia, and what to consider when managing state with SSR.
🧱 Why State Management Matters
When multiple components share data, relying only on props and events can quickly make the code complex.
State management puts shared data in a common location so components can read or update it directly. Nuxt offers two common approaches:
| Approach | Use case | Complexity |
|---|---|---|
useState | Simple state shared across components | Low |
| Pinia | Large applications and complex business logic | Medium |
useState is a lighter option.🚀 useState: Lightweight Built-in State
useState is a Nuxt composable for creating reactive, SSR-friendly shared state.
export function useCounter() {
return useState('counter', () => 0);
}
Use it in a component:
<template>
<div>
<p>Count:{{ count }}</p>
<button @click="count++">Increment</button>
</div>
</template>
<script setup>
const count = useCounter();
</script>
useState is a unique key identifying the state. Use different keys for distinct state values to avoid collisions.🔄 Sharing State Across Components
useState shares state by key, so components using the same key access the same data.
<template>
<button @click="count++">Increment</button>
</template>
<script setup>
const count = useState('counter', () => 0);
</script>
<template>
<p>Current count:{{ count }}</p>
</template>
<script setup>
const count = useState('counter', () => 0);
</script>
Clicking the button in AddButton also updates the number in ShowCount.
useState in a function in composables/ so components do not need to manage keys or risk mistyping them.⚡ Pinia: Managing Complex State
Use Pinia for complex state logic that needs actions, getters, or modular organization. Pinia provides an official Nuxt integration.
Install Pinia:
npm install @pinia/nuxt pinia
@pinia/nuxt and pinia compatible with Nuxt ^3.16.0.Add the module in nuxt.config.ts:
export default defineNuxtConfig({
modules: ['@pinia/nuxt'],
});
Create a store:
import { defineStore } from 'pinia';
export const useUserStore = defineStore('user', {
state: () => ({
name: 'Guest',
isLogin: false,
}),
actions: {
login(name) {
this.name = name;
this.isLogin = true;
},
},
});
Use it in a component:
<template>
<div>
<p>Username:{{ userStore.name }}</p>
<button v-if="!userStore.isLogin" @click="userStore.login('Alex')">Log in</button>
</div>
</template>
<script setup>
const userStore = useUserStore();
</script>
🆚 Choosing Between useState and Pinia
| Scenario | Recommended approach |
|---|---|
| Sharing a small state value, such as a theme or dialog visibility | useState |
| Actions, getters, or modular stores | Pinia |
| Complex state frequently read and updated by multiple components | Pinia |
| Quickly synchronizing data across a few components | useState |
useState for simple state reduces boilerplate.🪤 State Considerations for SSR
State created with useState is automatically included in the server-rendered page payload and reused during hydration. This allows the initial page to display the correct state without flickering.
However, do not put non-serializable data in useState, such as functions, DOM nodes, or objects with circular references, as this can cause SSR errors.
// ❌ Incorrect: functions cannot be serialized
const fn = useState('fn', () => () => {});
// ✅ Correct: use plain objects, arrays, and primitives
const user = useState('user', () => ({ name: 'Alex', age: 18 }));
❓ Questions and Answers
Q1: How does useState differ from Vue's ref?
useState uses a ref internally and adds SSR payload transfer and state sharing across components.
Q2: Do two components using the same useState key stay in sync?
Yes. useState maintains shared state under that key.
Q3: Is Pinia required in Nuxt?
No. useState is sufficient for simple projects; use Pinia when the complexity calls for it.
Q4: Why must useState data be serializable?
SSR requires data to travel from the server to the client. Non-serializable data cannot be transferred safely.
🧪 Practice
Build a theme switcher:
- In
app/composables/useTheme.js, useuseStateto createthemewith the default value'light'. - Create
app/components/ThemeToggle.vuewith a button that toggles between'light'and'dark'. - Create
app/components/ThemeDisplay.vueto display the current theme. - Use both components in
app/pages/index.vueand verify that their state stays in sync.
export function useTheme() {
// Create the state with useState here
}
<template>
<button @click="toggle">Toggle theme</button>
</template>
<script setup>
// Access theme and implement toggling here
</script>
🎉 You now understand state management in Nuxt! Next, we will explore nuxt.config.ts, rendering modes, and deployment.
