State Management

Learn to use useState and integrate Pinia in Nuxt, and choose the right state management approach for each situation.

🎯 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:

ApproachUse caseComplexity
useStateSimple state shared across componentsLow
PiniaLarge applications and complex business logicMedium
If you already know Pinia, you can use it in Nuxt. For a small piece of shared state, useState is a lighter option.

🚀 useState: Lightweight Built-in State

useState is a Nuxt composable for creating reactive, SSR-friendly shared state.

app/composables/useCounter.js
export function useCounter() {
    return useState('counter', () => 0);
}

Use it in a component:

app/pages/index.vue
<template>
    <div>
        <p>Count:{{ count }}</p>
        <button @click="count++">Increment</button>
    </div>
</template>

<script setup>
const count = useCounter();
</script>
The first argument to 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.

app/components/AddButton.vue
<template>
    <button @click="count++">Increment</button>
</template>

<script setup>
const count = useState('counter', () => 0);
</script>
app/components/ShowCount.vue
<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.

Wrap 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
This course uses Node.js v22.0.0 and recent versions of @pinia/nuxt and pinia compatible with Nuxt ^3.16.0.

Add the module in nuxt.config.ts:

nuxt.config.ts
export default defineNuxtConfig({
    modules: ['@pinia/nuxt'],
});

Create a store:

app/stores/user.js
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:

app/pages/index.vue
<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>
The Pinia course covers its API in detail. Here, we focus on integrating and using it in Nuxt.

🆚 Choosing Between useState and Pinia

ScenarioRecommended approach
Sharing a small state value, such as a theme or dialog visibilityuseState
Actions, getters, or modular storesPinia
Complex state frequently read and updated by multiple componentsPinia
Quickly synchronizing data across a few componentsuseState
You do not need Pinia for every state value just to follow a uniform pattern. Using 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:

  1. In app/composables/useTheme.js, use useState to create theme with the default value 'light'.
  2. Create app/components/ThemeToggle.vue with a button that toggles between 'light' and 'dark'.
  3. Create app/components/ThemeDisplay.vue to display the current theme.
  4. Use both components in app/pages/index.vue and verify that their state stays in sync.
app/composables/useTheme.js
export function useTheme() {
    // Create the state with useState here
}
app/components/ThemeToggle.vue
<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.