createStore
Registers a named store with initial state. Use setStore to mutate it and useStore or getStore to read it.
Signature
function createStore<State>(
name: string,
initialState: State,
options?: StoreOptions<State>
): voidParameters
| Parameter | Type | Description |
|---|---|---|
| name | string | Unique store key. Calling createStore twice with the same name is a no-op. |
| initialState | State | Plain object representing the initial state snapshot. |
| options | StoreOptions<State> (optional) | Configuration for persistence, sync, DevTools, SSR behaviour, etc. |
Return value
Returns void. Interact with the store viasetStore, getStore, anduseStore.
Example
example.ts
import { createStore, setStore, getStore, useStore } from 'stroid'
// Declare once
createStore('counter', { count: 0 }, { devtools: true, persist: { key: 'counter', driver: localStorage } })
// Update
export const increment = () =>
setStore('counter', (d) => {
d.count += 1
})
// Read outside React
console.log(getStore('counter').count) // 0
// React component
export function Counter() {
const count = useStore('counter', (s) => s.count)
return <button onClick={increment}>Count: {count}</button>
}