UNPKG

react18-global-store

Version:

A simple yet elegant, light weight, react18 global store to replace Zustand for better tree shaking.

47 lines (46 loc) 2.04 kB
type Listener = () => void; export type SetterArgType<T> = T | ((prevState: T) => T); export type SetStateAction<T> = (value: SetterArgType<T>) => void; export type ValueType<T> = T | (() => T); /** * This is a hack to reduce lib size + readability + not encouraging direct access to globalThis */ type RGS = { v: unknown; l: Listener[]; s: SetStateAction<unknown> | null; }; declare global { var rgs: Record<string, RGS | undefined>; } export declare const globalRGS: Record<string, RGS | undefined>; /** setter function to set the state. */ export declare const createSetter: <T>(key: string) => SetStateAction<unknown>; /** Extract coomon create hook logic to utils */ export declare const createHook: <T>(key: string) => [T, SetStateAction<T>]; type Mutate<T> = (value?: T) => void; export type Plugin<T> = { init?: (key: string, value: T | undefined, mutate: Mutate<T>) => void; onChange?: (key: string, value?: T) => void; }; /** Initialize the named store when invoked for the first time. */ export declare const initWithPlugins: <T>(key: string, value?: ValueType<T>, plugins?: Plugin<T>[], doNotInit?: boolean) => void; /** * Use this hook similar to `useState` hook. * The difference is that you need to pass a * unique key - unique across the app to make * this state accessible to all client components. * * @example * ```tsx * const [state, setState] = useRGS<number>("counter", 1); * ``` * * @param key - Unique key to identify the store. * @param value - Initial value of the store. * @param plugins - Plugins to be applied to the store. * @param doNotInit - Do not initialize the store. Useful when you want to initialize the store later. Note that the setter function is not available until the store is initialized. * @returns - A tuple (Ordered sequance of values) containing the state and a function to set the state. */ export declare const useRGSWithPlugins: <T>(key: string, value?: ValueType<T>, plugins?: Plugin<T>[], doNotInit?: boolean) => [T, SetStateAction<T>]; export {};