diff --git a/docs/content/3.docs/1.usage/2.state.md b/docs/content/3.docs/1.usage/2.state.md index 378cfe7696..6a21ab774b 100644 --- a/docs/content/3.docs/1.usage/2.state.md +++ b/docs/content/3.docs/1.usage/2.state.md @@ -1,44 +1,68 @@ # State -Nuxt provides `useState` to create a globally shared state. +Nuxt provides `useState` to create a globally shared state within the context. -## `useState` +`useState` is SSR-friendly `ref` replacement in that its value will be hydrated (preserved) after server-side rendering and is shared across all components using a unique key. -Within your pages, components and plugins you can use `useState`. It can be used to create your own store implementation. +::alert{icon=⚠️} +Never define `const state = ref()` outside of ` -### Example + +``` + +## Example In this example, we use a server-only plugin to find about request locale. -```ts [plugins/locale.server.ts] -import { defineNuxtPlugin, useState } from '#app' +```ts [composables/states.ts] +export const useLocale = () => useState('locale', () => 'en') +``` -export default defineNuxtPlugin((nuxt) => { - const locale = useState( - 'locale', - () => nuxt.ssrContext.req.headers['accept-language']?.split(',')[0] - ) +```ts [plugins/locale.server.ts] +export default defineNuxtPlugin((nuxtApp) => { + const locale = useLocale() + locale.value = nuxtApp.ssrContext?.req.headers['accept-language']?.split(',')[0] }) ``` -```vue +```vue [app.vue] diff --git a/examples/use-state/composables/states.ts b/examples/use-state/composables/states.ts new file mode 100644 index 0000000000..b142eba6e9 --- /dev/null +++ b/examples/use-state/composables/states.ts @@ -0,0 +1 @@ +export const useLocale = () => useState('locale') diff --git a/examples/use-state/plugins/locale.server.ts b/examples/use-state/plugins/locale.server.ts index 52ed70d8b6..e206f486cc 100644 --- a/examples/use-state/plugins/locale.server.ts +++ b/examples/use-state/plugins/locale.server.ts @@ -1,6 +1,4 @@ -import { useState } from '#app' - -export default defineNuxtPlugin((nuxt) => { - const locale = useState('locale') - locale.value = nuxt.ssrContext.req.headers['accept-language']?.split(',')[0] +export default defineNuxtPlugin((nuxtApp) => { + const locale = useLocale() + locale.value = nuxtApp.ssrContext?.req.headers['accept-language']?.split(',')[0] })