react-hooks-global-state-next
Version:
Simple global state for React with Hooks API without Context API
27 lines (26 loc) • 1.26 kB
TypeScript
import { SetStateAction } from 'react';
/**
* Create a global state.
*
* It returns a set of functions
* - `useGlobalState`: a custom hook works like React.useState
* - `getGlobalState`: a function to get a global state by key outside React
* - `setGlobalState`: a function to set a global state by key outside React
* - `subscribe`: a function that subscribes to state changes
*
* @example
* import { createGlobalState } from 'react-hooks-global-state-next';
*
* const { useGlobalState } = createGlobalState({ count: 0 });
*
* const Component = () => {
* const [count, setCount] = useGlobalState('count');
* ...
* };
*/
export declare const createGlobalState: <State extends object>(initialState: State) => {
useGlobalState: <StateKey extends keyof State>(stateKey: StateKey) => readonly [State[StateKey], (u: SetStateAction<State[StateKey]>) => void];
getGlobalState: <StateKey_1 extends keyof State>(stateKey: StateKey_1) => State[StateKey_1];
setGlobalState: <StateKey_2 extends keyof State>(stateKey: StateKey_2, update: SetStateAction<State[StateKey_2]>) => void;
subscribe: <StateKey_3 extends keyof State>(stateKey: StateKey_3, listener: (value: State[StateKey_3]) => void) => void;
};