Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Comprehensive Nuxt 3.x reference covering SSR, file-based routing, auto-imports, server routes, and Nitro deployment.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/features-state.md
1---2name: state-management3description: useState composable and SSR-friendly state management in Nuxt4---56# State Management78Nuxt provides `useState` for SSR-friendly reactive state that persists across components.910## useState1112SSR-safe replacement for `ref` that shares state across components:1314```vue15<script setup lang="ts">16// State is shared by key 'counter' across all components17const counter = useState('counter', () => 0)18</script>1920<template>21<div>22Counter: {{ counter }}23<button @click="counter++">+</button>24<button @click="counter--">-</button>25</div>26</template>27```2829## Creating Shared State3031Define reusable state composables:3233```ts34// composables/useUser.ts35export function useUser() {36return useState<User | null>('user', () => null)37}3839export function useLocale() {40return useState('locale', () => 'en')41}42```4344```vue45<script setup lang="ts">46// Same state instance everywhere47const user = useUser()48const locale = useLocale()49</script>50```5152## Initializing State5354Use `callOnce` to initialize state with async data:5556```vue57<script setup lang="ts">58const config = useState('site-config')5960await callOnce(async () => {61config.value = await $fetch('/api/config')62})63</script>64```6566## Best Practices6768### ❌ Don't Define State Outside Setup6970```ts71// ❌ Wrong - causes memory leaks and shared state across requests72export const globalState = ref({ user: null })73```7475### ✅ Use useState Instead7677```ts78// ✅ Correct - SSR-safe79export const useGlobalState = () => useState('global', () => ({ user: null }))80```8182## Clearing State8384```ts85// Clear specific state86clearNuxtState('counter')8788// Clear multiple states89clearNuxtState(['counter', 'user'])9091// Clear all state (use with caution)92clearNuxtState()93```9495## With Pinia9697For complex state management, use Pinia:9899```bash100npx nuxi module add pinia101```102103```ts104// stores/counter.ts105export const useCounterStore = defineStore('counter', {106state: () => ({107count: 0,108}),109actions: {110increment() {111this.count++112},113},114})115```116117```ts118// stores/user.ts (Composition API style)119export const useUserStore = defineStore('user', () => {120const user = ref<User | null>(null)121const isLoggedIn = computed(() => !!user.value)122123async function login(credentials: Credentials) {124user.value = await $fetch('/api/login', {125method: 'POST',126body: credentials,127})128}129130return { user, isLoggedIn, login }131})132```133134```vue135<script setup lang="ts">136const counterStore = useCounterStore()137const userStore = useUserStore()138139// Initialize store data once140await callOnce(async () => {141await userStore.fetchUser()142})143</script>144```145146## Advanced: Locale Example147148```ts149// composables/useLocale.ts150export function useLocale() {151return useState('locale', () => useDefaultLocale().value)152}153154export function useDefaultLocale(fallback = 'en-US') {155const locale = ref(fallback)156157if (import.meta.server) {158const reqLocale = useRequestHeaders()['accept-language']?.split(',')[0]159if (reqLocale) locale.value = reqLocale160}161else if (import.meta.client) {162const navLang = navigator.language163if (navLang) locale.value = navLang164}165166return locale167}168```169170## State Serialization171172`useState` values are serialized to JSON. Avoid:173174- Functions175- Classes176- Symbols177- Circular references178179```ts180// ❌ Won't work181useState('fn', () => () => console.log('hi'))182useState('instance', () => new MyClass())183184// ✅ Works185useState('data', () => ({ name: 'John', age: 30 }))186useState('items', () => ['a', 'b', 'c'])187```188189<!--190Source references:191- https://nuxt.com/docs/getting-started/state-management192- https://nuxt.com/docs/api/composables/use-state193- https://nuxt.com/docs/api/utils/clear-nuxt-state194-->195