Nuxt/docs/content/3.docs/1.usage/2.state.md
2021-10-11 23:49:54 +02:00

974 B

State

Nuxt provides useState to create a globally shared state.

useState

Within your pages, components and plugins you can use useState. It can be used to create your own store implementation.

You can think of it as an SSR-friendly ref in that its value will be hydrated (preserved) after server-side rendering. It is shared across all components.

Usage

useState(key: string)
  • key: a unique key to ensure that data fetching can be properly de-duplicated across requests

Example

In this example, we use a server-only plugin to find about request locale.

import { defineNuxtPlugin, useState } from '#app'

export default defineNuxtPlugin((nuxt) => {
  const locale = useState('locale')
  locale.value = nuxt.ssrContext.req.headers['accept-language']?.split(',')[0]
})
<script setup>
const locale = useState('locale')
</script>

<template>
  Current locale: {{ locale }}
</template>