useState()
Creates SSR-friendly shared reactive state hydrated from server to client.
Syntax
const state = useState(key, init?) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
key | string | Yes | A unique key identifying the state across server and client. |
init | () => T | No | Factory returning the initial value. Run only once on the server then serialized into the payload for client hydration. |
Returns
Ref<T> — A reactive ref shared by key across the app.
Examples
<script setup lang="ts">
const counter = useState('counter', () => 0)
</script>
<template>
<button @click="counter++">{{ counter }}</button>
</template>
// composables/useAuth.ts — share user state app-wide
export const useUser = () =>
useState<User | null>('user', () => null)
Notes
Prefer `useState` over a module-level `ref` because plain refs are
shared across requests on the server, leaking data between users.
State is serialized into the SSR payload, so keep values JSON
serializable. The init factory does not re-run on the client during
hydration.