Skip to content
stroid
Docsapicreate store
Docs for v0.0.2 - current npm release. Reduce your code, reduce your stress - never your functionality.

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>
): void

Parameters

ParameterTypeDescription
namestringUnique store key. Calling createStore twice with the same name is a no-op.
initialStateStatePlain object representing the initial state snapshot.
optionsStoreOptions<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>
}