Skip to content

nexa-state

Global and local state management built on top of Nexa signals.

createStore

Creates a reactive store from a plain object. Each property becomes a Signal.

ts
import { createStore } from 'nexa-state'

function createStore<T extends Record<string, any>>(
  initialState: T
): { state: { [K in keyof T]: Signal<T[K]> } }

Returns an object with a state property where each key is a signal.

Example:

ts
const { state } = createStore({ count: 0, text: 'hello' })
state.count.value = 5
state.text.value = 'world'

defineStore

Defines a singleton store that is lazily instantiated on first use.

ts
import { defineStore } from 'nexa-state'

function defineStore<T>(
  id: string,
  factory: () => T
): () => T

Returns a hook function that returns the singleton instance.

Example:

ts
import { createStore, defineStore } from 'nexa-state'
import { computed } from 'nexa-reactivity'

export const useCounter = defineStore('counter', () => {
  const { state } = createStore({ count: 0 })
  const increment = () => state.count.value++
  const doubled = computed(() => state.count.value * 2)
  return { state, increment, doubled }
})

// In a component:
const counter = useCounter()
counter.increment()

persist

Creates a signal that automatically persists to storage.

ts
import { persist } from 'nexa-state'

function persist<T>(
  key: string,
  initial: T,
  storage?: StorageLike
): Signal<T>
ParameterDescription
keylocalStorage key used to serialize and restore the value
initialDefault value when no stored value exists
storageOptional storage backend (defaults to localStorage)

The returned signal automatically saves to storage on every write and reads the saved value on initialization. If stored data is corrupted (invalid JSON), it falls back to the initial value.

Example:

ts
const theme = persist('theme', 'light')
theme.value = 'dark'  // auto-saves to localStorage

Separate Persistence Package

For component-level persistence with signals, use the standalone nexa-persistence package:

ts
import { persistSignal } from 'nexa-persistence'

Released under the MIT License.