Skip to main content

GlobalStateProvider

import { GlobalStateProvider } from '@dr.pogodin/react-global-state';

Provides GlobalState to its children tree.

Generic Parameters

In TypeScript version GlobalStateProvider is a generic component with the signature:

function GlobalStateProvider<StateT>(
props: GlobalStateProviderProps<StateT>,
): JSX.Element;

where a single generic parameter:

tip

Alternatively you may use withGlobalStateType() function to get GlobalStateProvider with "locked-in" StateT:

import { withGlobalStateType } from '@dr.pogodin/react-global-state';

const { GlobalStateProvider } = withGlobalStateType<StateT>();

Properties

info

In TypeScript version props of GlobalStateProvider are typed this way:

type GlobalStateProviderProps<StateT> = {
children?: ReactNode;
} & ({
initialState: ValueOrInitializerT<StateT>,
ssrContext?: SsrContext<StateT>;
} | {
stateProxy: true | GlobalState<StateT>;
});

Note, in particular, this type permits to either provide stateProxy prop, to use GlobalStateProvider as a proxy for an existing GlobalState, or a pair of initialState and (optionally) ssrContext props, to create and provide a new GlobalState.

In JavaScript, where all these props (stateProxy, initialState, ssrContext) can be provided together, the stateProxy, if provided, has precedence and activates the "proxy mode", no matter other props values.

  • childrenReactNode — Component children, if any, are rendered in-place of GlobalStateProvider and provided with GlobalState instance.

  • initialState ValueOrInitializerT<StateT> — The initial global state content.

    BEWARE

    The library assumes the initialState is never mutated after it has been provided to GlobalStateProvider.

    JavaScript vs. TypeScript

    In TypeScript version this property is obligatory (beside when stateProxy prop is used instead), and its value must satisfy the ValueOrInitializerT<StateT> type.

    in JavaScript it is optional, as the runtime logic permits to initialize entire global state as undefined, and later create and populate the state object as its various paths are accessed via global state hooks.

    In theory, you can do the same in TypeScript (by defining StateT as optionally undefined), but that will make TypeScript unable to evaluate types of values inside the state, thus diminishing the usefulness of TypeScript features provided by this library.

  • ssrContextSsrContext — Optional. SSR (server-side rendering) context. In TypeScript version it is only permitted when no stateProxy is provided.

  • stateProxy boolean | GlobalState — Enables proxy mode, intended for code-splitting and SSR implementation: