State Management

Nuxt provides useState composable to create a reactive and SSR-friendly shared state across components.

useState is an SSR-friendly ref replacement. Its value will be preserved after server-side rendering (during client-side hydration) and shared across all components using a unique key.

👉

Read more in API > Composables > Use State.

👉

useState only works during setup or Lifecycle Hooks.

Best practices

🚨

Never define const state = ref() outside of <script setup> or setup() function.
Such state will be shared across all users visiting your website and can lead to memory leaks!

Instead use const useX = () => useState('x')

Examples

Basic usage

In this example, we use a component-local counter state. Any other component that uses useState('counter') shares the same reactive state.

app.vue

  1. <script setup>
  2. const counter = useState('counter', () => Math.round(Math.random() * 1000))
  3. </script>
  4. <template>
  5. <div>
  6. Counter: {{ counter }}
  7. <button @click="counter++">
  8. +
  9. </button>
  10. <button @click="counter--">
  11. -
  12. </button>
  13. </div>
  14. </template>

🔎

Read and edit a live example in Examples > Composables > Use State

👉

Read more in API > Composables > Use State.

Advanced

In this example, we use a composable that detects the user’s default locale from the HTTP request headers and keeps it in a locale state.

🔎

Read and edit a live example in Examples > Other > Locale

Shared state

By using auto-imported composables we can define global type-safe states and import them across the app.

composables/states.ts

  1. export const useCounter = () => useState<number>('counter', () => 0)
  2. export const useColor = () => useState<string>('color', () => 'pink')

app.vue

  1. <script setup>
  2. const color = useColor() // Same as useState('color')
  3. </script>
  4. <template>
  5. <p>Current color: {{ color }}</p>
  6. </template>