Skip to main content

GlobalState

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

The GlobalState class implements container that holds and manages the global state content. Users are not supposed to create new GlobalState instances explicitly, but they may access the current instance via the getGlobalState() hook. It allows imperative interactions with the global state, instead of the normal declarative state access via the useGlobalState() hook.

Generic Parameters

In TypeScript this class is a generic

class GlobalState<StateT>;

where the signle generic parameter is:

  • StateT — The global state content type.

Methods

constructor()

constructor GlobalState<StateT>(
initialState: StateT,
ssrContext?: SsrContext<StateT>
): GlobalState<StateT>;

Creates a new GlobalState instance with given initialState, and optionally ssrContext.

  • initialStateStateT — Initial content of the global state. In JS it may be omitted to start with undefined state, but in TS the typing forces it to be given.
  • ssrContextSsrContext<StateT> — Optionally the SsrContext instance (for SSR purposes).

get()

globalState.get(path, options)

Gets current or initial value at the specified path of the global state. It allows to get the entire global state, and automatically sets default value at the path.

Runtime implementation:

globalState.get<ValueT>(
path?: null | string,
options? GetOptsT<ValueT>,
): ValueT;
  • pathnull | string | undefined — Optional. Dot-delimitered state path. If null or undefined the entire global state is returned.

  • optionsGetOptsT<ValueT> — Optional. Additional settings.

    • initialStateboolean — If true the value will be read from the initial global state (at the moment of the GlobalState construction), instead of the current global state.

    • initialValueValueOrInitializerT<ValueT> — Optional. Intended initial value at path, or its initializing function. In case undefined value was read from the state path (either from the current, or initial state, depending on the initialState flag), this initialValue (its result) will be returned to the caller instead. initialValue (its result) will be also written to the path of the current state, provided the current value there is undefined.

  • Returns the value at the path (of ValueT type).

Compile-time TypeScript overloads:

  1. When called without arguments it returns entire state content as a whole (effectively, it is the same as the getEntireState() method):

    globalState.get(): StateT;
  2. If StateT and the type of path (PathT) allow to auto-evaluate the type of value at path (ValueArgT and ValueResT), this overload gets the value with type-checks:

    get<PathT extends null | string | undefined, ValueArgT, ValueResT>(
    path: PathT,
    opts?: GetOptsT<ValueArgT>,
    ): ValueResT;

    Simplified by omitting the exact definitions behind ValueArgT and ValueResT.

    If StateT and PathT do not allow to evaluate the value type, ValueArgT falls back to never, and ValueResT falls back to void, thus rendering this overload forbidden in any practical context.

  3. This implementation allows to force any value type at the caller's discretion:

    get<Forced extends ForceT | false = false, ValueT = void>(
    path?: null | string,
    opts?: GetOptsT<ValueT>,
    ): ValueT;

    Simplified by omitting some details behind the actual ValueT definition and usage.

    By default, the false value of Forced generic param forbids compiler to use this overload; it must be set equal ForceT to work, e.g.

    // Forces TypeScript to assume the value at `path` has "string" type.

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

    globalState.get<ForceT, string>(path);

getEntireState()

globalState.getEntireState(): StateT;

Returns entire state content as a whole. It is equivalent to globalState.get().

set()

globalState.set(path, value);

Runtime implementation:

globalState.set<ValueT>(
path: null | string | undefined,
value: ValueT,
): ValueT;
  • pathnull | string | undefined — Optional. Dot-delimitered state path. If null or undefined the value will replace the entire global state content.

  • valueunknown — The value to set.

  • Returns the given value itself.

Compile-time TypeScript overloads:

  1. If StateT and path type (PathT) allow to auto-evaluate the type of value at the path, this overload allows to write the value with static type-checks:

    set<PathT extends null | string | undefined, ValueArgT, ValueResT>(
    path: PathT,
    value: ValueArgT,
    ): ValueResT;

    Simplified by ommiting details behind the actual ValueArgT and ValueResT definitions and use.

    If value type cannot be evaluated based on StateT and PathT, ValueArgT falls back to never, and ValueResT falls back to unknown, thus forbidding TypeScript to use this overload in any practical context.

  2. This overload allows to force any ValueT type at the caller's discretion:

    set<Forced extends ForceT | false = false, ValueT = never>(
    path: null | string | undefined,
    value: ValueT,
    ): ValueT;

    Simplified by omitting details behind the actual ValueT definition and use.

    The default value of Forced generic parameter, false, forbids TypeScript to use this overload, unless Forced is explicitly set equal ForcedT, i.e. you use this overload like this:

    // Forces TypeScript to assume `value` has "string" type:

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

    globalState.set<ForceT, string>('some.path', 'some string value');

setEntireState()

globalState.setEntireState(value: StateT): StateT;

Writes entire state content as a whole. It is equivalent to globalState.set(null, value).

  • valueStateT — The new state content.
  • Returns given value for chaining convenience.

unWatch()

globalState.unWatch(callback: CallbackT);

Unsubscribes callback from the state update notifications; no operation if callback is not subscribed.

  • callbackCallbackT — The callback to unsubscribe.
caution

This method throws if SsrContext is attached to the state instance: the state watching functionality is intended for the client side only.

watch()

globalState.watch(callback: CallbackT);

Subscribes callback to watch state updates; no operation if callback is already subscribed to this state instance.

  • callbackCallbackT — It will be triggered without any arguments each time the state context changes (however, the library may combine several independent state updates and call this callback just once when all these updatesare completed).
caution

This method throws if SsrContext is attached to the state instance: the state watching functionlity is intended for the client-side only.