Skip to content
react-global-state-hooks

Global state API

Reference for createGlobalState, its options, lifecycle callbacks and the members of the hook.

API referenceTypeScriptTry an example

createGlobalState

ts
createGlobalState(initialState, options?) => hook

initialState is a value or a function returning one. Without options, the hook’s second tuple item is a setState function. With actions, it is the actions object.

Options

OptionTypePurpose
namestringName shown in DevTools and used for debugging.
metadatavalue or functionNon-reactive side data. Available as the tuple’s third item and as store.metadata.
actionsRecord<string, (...args) => (tools) => any>Named state changes. See Actions.
callbacksobjectLifecycle hooks, below.
localStorageobjectPersistence (web package). See Persistence.

Callbacks

callbacks.ts
import { createGlobalState } from 'react-global-state-hooks';

export const log: string[] = [];

export const useGuarded = createGlobalState(
  { count: 0 },
  {
    name: 'guarded-counter',
    metadata: { changes: 0 },
    callbacks: {
      // Runs when the store is created. May return a cleanup function.
      onInit: ({ getState }) => {
        log.push(`init:${getState().count}`);

        return () => log.push('cleanup');
      },

      // Runs after each accepted state change.
      onStateChanged: ({ previousState, state, setMetadata }) => {
        log.push(`changed:${previousState.count}->${state.count}`);
        setMetadata((metadata: { changes: number }) => ({ changes: metadata.changes + 1 }));
      },

      // Return true to reject a change before it is applied.
      computePreventStateChange: ({ state }) => state.count < 0,
    },
  },
);
CallbackWhen it runs
onInit(tools)When the store is created and again after reset(). Return a cleanup function to run before the next reset() or dispose().
onStateChanged({ previousState, state, ...tools })After a state change is applied.
onSubscribed(tools, subscription)Each time a subscription is added.
computePreventStateChange({ previousState, state, ...tools })Before a change is applied. Return true to reject it.
onUnMount(store)When a context provider unmounts. Only applies to contexts.

The hook

useStore(selector?, depsOrOptions?) returns [selected, setStateOrActions, metadata].

OptionPurpose
dependenciesValues the selector reads from outside the store.
isEqual(current, next)Compare the selected value. Default ===.
isEqualRoot(current, next)Compare the whole state. Default ===.

Store members

MemberSignatureNotes
getState() => State
setState(valueOrUpdater, { forceUpdate?, identifier? }?) => voidforceUpdate notifies even when the reference is unchanged. identifier labels the change in DevTools.
subscribe(callback) or (selector, callback, options?)options: skipFirst, isEqual, isEqualRoot. Returns an unsubscribe function.
select(selector, depsOrOptions?) => SelectedHook that returns only the selection.
createSelectorHook(selector, { isEqual?, isEqualRoot?, name? }?) => hookRead-only shared hook that returns the value. Chains.
createObservable(selector, { isEqual?, isEqualRoot?, name? }?) => observableSubscribable and chainable.
metadataMetadata (getter)
getMetadata / setMetadata() => Metadata / (valueOrUpdater) => voidgetMetadata is deprecated in favour of metadata.
reset() => void or (state, metadata) => voidA test helper: restores the initial state and re-runs onInit. Function initializers are re-evaluated.
dispose() => voidRemoves subscriptions and runs cleanup.
actionsobject or nullThe actions object.
usehookThe same function as the hook.
Documentation
↑↓ Navigate ↵ Open Esc CloseRGSH docs
Get started

Shared state. Precise subscriptions.
Built-in DevTools.