Nuxt & Universal SSR (50 Qs)•Part 3: Advanced Internals, Performance & Production (Senior / Staff)
Nuxt 3 `useState()` vs Pinia: SSR Hydration and Cross-Request Leak Prevention.
senior LevelCode ExampleHooksState ManagementForms
In Simple Words:
useState(): Built-in Nuxt primitive that creates an SSR-friendly, reactive ref shared across components. During SSR, state is serialized into the HTML payload and hydrated on the client without re-executing initializers.- Why not vanilla
ref()outside components?: A module-levelconst state = ref()in a Node.js SSR server is shared across all concurrent requests from different users, leaking private data!useState()scopes state uniquely per request.
typescript
// composables/useUser.ts
export const useAuthUser = () => {
// Key 'auth_user' ensures unique hydration bridge between server and client
return useState<User | null>('auth_user', () => null);
};