Skip to content

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++ // Reactive

Signature

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

ScenarioSolution
Simple shared state between componentsuseState
Complex state with actions and gettersPinia (via @kimesh/pinia module)
Server-fetched data with cachinguseQuery / useKmFetch
Route-specific loader datauseLoaderData

Next Steps

Released under the MIT License.