UNPKG

@ibahmani007/stately

Version:

Minimal, powerful global state manager for React

50 lines (49 loc) 1.43 kB
// src/index.ts import { useSyncExternalStore } from "react"; function getKey(name) { return `__stately__${name ?? "default"}`; } function loadPersistedState(defaultState, options) { if (typeof window === "undefined" || !options?.persist) return defaultState; const raw = localStorage.getItem(getKey(options.name)); if (!raw) return defaultState; try { return JSON.parse(raw); } catch { return defaultState; } } function createStore(initialValue, options) { let state = loadPersistedState(initialValue, options); const listeners = /* @__PURE__ */ new Set(); const middlewares = options?.middlewares ?? []; const notify = () => { listeners.forEach((listener) => listener()); if (options?.devtools && typeof window !== "undefined") { window.__STATELY_DEVTOOLS__?.({ name: options.name, state }); } }; const setState = (updater) => { const nextState = updater(state); middlewares.forEach((mw) => mw(state, nextState)); state = nextState; if (options?.persist) { localStorage.setItem(getKey(options.name), JSON.stringify(state)); } notify(); }; const subscribe = (listener) => { listeners.add(listener); return () => listeners.delete(listener); }; const useStore = () => { const snapshot = useSyncExternalStore(subscribe, () => state); return [snapshot, setState]; }; return useStore; } export { createStore };