State Management
Kimesh provides useState — a reactive, SSR-friendly state composable for sharing state across components.
useState
ts
// Auto-imported
const count = useState('counter', () => 0)
count.value++ // ReactiveSignature
ts
function useState<T>(key: string, init?: () => T): Ref<T>key— Unique string key for the state. Must be unique across your application.init— Optional factory function to initialize the value. Called only once.
Usage in Components
vue
<script setup>
// State is shared across all components using the same key
const user = useState('user', () => ({ name: 'Guest', loggedIn: false }))
</script>
<template>
<p>Hello, {{ user.name }}</p>
</template>Shared State Pattern
Create a composable for reusable shared state:
ts
// composables/useCounter.ts
export function useCounter() {
const count = useState('counter', () => 0)
function increment() {
count.value++
}
function decrement() {
count.value--
}
return { count, increment, decrement }
}vue
<!-- Any component -->
<script setup>
// useCounter is auto-imported from composables/
const { count, increment, decrement } = useCounter()
</script>
<template>
<button @click="decrement">-</button>
<span>{{ count }}</span>
<button @click="increment">+</button>
</template>Utility Functions
clearKmState
Clear a specific state value:
ts
clearKmState('counter') // Removes state with key 'counter'hasKmState
Check if a state exists:
ts
if (hasKmState('user')) {
// State exists
}getKmStateKeys
Get all registered state keys:
ts
const keys = getKmStateKeys() // ['counter', 'user', ...]When to Use
| Scenario | Solution |
|---|---|
| Simple shared state between components | useState |
| Complex state with actions and getters | Pinia (via @kimesh/pinia module) |
| Server-fetched data with caching | useQuery / useKmFetch |
| Route-specific loader data | useLoaderData |
Next Steps
- Head Management — Manage
<head>tags - Data Fetching — Data loading patterns