UNPKG

@ekwoka/preact-global-state

Version:
21 lines (20 loc) 704 B
import { signal } from '@preact/signals'; import { useCallback } from 'preact/hooks'; const store = {}; export const Store = (initialValues) => { Object.entries(initialValues).forEach(([key, value]) => { store[key] = signal(value); }); }; export const useGlobalSignal = (key, defaultValue = null) => { store[key] = store[key] ?? signal(defaultValue); return store[key]; }; export const useGlobalState = (key, defaultValue) => { const signal = useGlobalSignal(key, defaultValue); const set = useCallback((v) => { const newValue = v instanceof Function ? v(signal.value) : v; signal.value = newValue; }, [signal]); return [store[key].value, set]; };