How to manage state in Nuxt 3?
useState - Built-in
javascript
// composables/useCounter.ts
export const useCounter = () => {
const count = useState('counter', () => 0);
const increment = () => count.value++;
return { count, increment };
};
// In any component
const { count, increment } = useCounter();
// Shared across all components!Pinia - For Complex State
javascript
// stores/user.ts
export const useUserStore = defineStore('user', () => {
const user = ref(null);
const isLoggedIn = computed(() => !!user.value);
async function login(credentials) {
user.value = await $fetch('/api/login', {
method: 'POST',
body: credentials
});
}
return { user, isLoggedIn, login };
});
// In component
const userStore = useUserStore();
await userStore.login({ email, password });Comparison
| Feature | useState | Pinia |
|---|---|---|
| Setup | Zero | Minimal |
| SSR | Built-in | Supported |
| DevTools | No | Yes |
| Modularity | Manual | Built-in |
| Best for | Simple | Complex |
Best Practices
✅ useState for simple shared state ✅ Pinia for complex business logic ✅ Both are SSR-friendly ✅ Auto-hydration on client
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.