statelet
Version:
Dead simple state management built on kvkit - composable, reactive, shareable. Supports Standard Schema (Valibot, Zod, ArkType).
17 lines (16 loc) • 672 B
JavaScript
import { useSyncExternalStore, useCallback, useMemo } from 'react';
// Implementation
export function useStatelet(state, selector) {
const getSnapshot = useCallback(() => state.get(), [state]);
const subscribe = useCallback((onChange) => {
return state.subscribe(() => onChange());
}, [state]);
const value = useSyncExternalStore(subscribe, getSnapshot);
// If selector is provided, use useMemo to avoid unnecessary re-renders
if (selector) {
const selectedValue = useMemo(() => selector(value), [value, selector]);
return [selectedValue, state.set];
}
// Otherwise return the tuple
return [value, state.set];
}