r18gs
Version:
A simple yet elegant, light weight, react18 global store to replace Zustand for better tree shaking.
57 lines (56 loc) • 2.57 kB
TypeScript
type Listener = () => void;
type ListenerWithSelectors = {
l: Listener;
s: [includeRegExp?: RegExp | null, excludeRegExp?: RegExp];
};
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
*/
export type RGS = {
v: unknown;
l: ListenerWithSelectors[];
s: SetStateAction<unknown> | null;
};
declare global {
var rgs: Record<string, RGS | undefined>;
}
export declare const globalRGS: Record<string, RGS | undefined>;
/** trigger all listeners */
export declare const triggerListeners: <T>(rgs: RGS, oldV: T, newV: T) => void;
/** Extract coomon create hook logic to utils */
export declare const createHook: <T>(key: string, includeRegExp?: RegExp | null | 0, excludeRegExp?: RegExp) => [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, includeRegExp?: RegExp | null | 0, excludeRegExp?: RegExp) => [T, SetStateAction<T>];
/**
* Converts a list of selectors into a regular expression.
* @param list - An array of strings representing the fields to match.
* @returns A regular expression that matches any field from the provided list.
*/
export declare const listToRegExp: (list: string[]) => RegExp;
export {};