createStore
stableCreate a state store
Creates a new store instance with get, set, subscribe, and destroy methods.
Signature
createStore<T>(initializer: T | StateCreator<T>): Store<T>
Parameters
initializer
T | (set, get) => TRequiredEither a raw initial state object or a function that receives set and get and returns the initial state object.
Returns
Returns
Store<T>A store instance with get, set, subscribe, and destroy methods
Examples
Raw Object
The simplest way to create a store for data-only state:
import { createStore } from 'qortex-store';const userStore = createStore({name: 'John',loggedIn: false});// Update via external setuserStore.set({ loggedIn: true });
Initializer Function (Set/Get)
Use an initializer to define actions that have access to current state and updates:
const counterStore = createStore((set, get) => ({count: 0,// Use get() to read current stateincrement: () => set({ count: get().count + 1 }),// Use functional updates for atomic changesdecrement: () => set((s) => ({ count: s.count - 1 })),// Access other state properties within actionsresetIfHigh: () => {if (get().count > 10) set({ count: 0 });}}));
get()
Read the current state snapshot at any time:
const state = counterStore.get();console.log(state.count); // 0state.increment();console.log(counterStore.get().count); // 1
set() — All Variants
set supports partial merging, functional updates, and full replacement:
const store = createStore({ a: 1, b: 2 });// 1. Partial Merge (default)store.set({ a: 10 }); // { a: 10, b: 2 }// 2. Functional Updatestore.set((s) => ({ a: s.a + 1 })); // { a: 11, b: 2 }// 3. Full Replacementstore.set({ a: 0 }, true); // { a: 0 } (b is gone!)
subscribe()
Listen for state changes. Returns an unsubscribe function:
const unsub = counterStore.subscribe((state, prevState) => {console.log('Changed:', prevState.count, '→', state.count);});// Stop listeningunsub();
destroy()
Remove all listeners and reset state to the initial value:
counterStore.destroy();// All listeners removed, state reset to initial