Skip to content
react-global-state-hooks

Metadata and non-reactive access

Read and change state outside components, subscribe to changes, and keep side data that never triggers renders.

GuideTypeScriptTry an example

The problem this solves

Not everything that lives next to state should cause a render: request counters, timestamps, a “last synced” label you only read in handlers. And not every reader of state is a component: API clients, WebSocket handlers and analytics need it too.

Non-reactive access

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

export const useSession = createGlobalState({ token: null as string | null });

export function authHeader(): Record<string, string> {
  // Read the current value from any module, no hook required.
  const { token } = useSession.getState();

  return token ? { Authorization: `Bearer ${token}` } : {};
}

export function signIn(token: string) {
  useSession.setState({ token });
}

// Subscribe to a slice. The callback runs immediately with the current value, then on every change.
export const unsubscribe = useSession.subscribe(
  (state) => state.token,
  (token) => {
    console.log('token changed:', token);
  },
);
  • getState() reads the current value.
  • setState(valueOrUpdater) writes it and notifies subscribers.
  • subscribe(selector, callback) listens to a slice. The callback runs immediately with the current value unless you pass { skipFirst: true }. It returns a function that unsubscribes.

Metadata

Metadata is a second object stored beside the state. Changing it never re-renders anything.

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

export const useFeed = createGlobalState(
  { items: [] as string[] },
  { metadata: { lastFetchedAt: null as number | null, requests: 0 } },
);

export function recordRequest() {
  // Changing metadata never re-renders components.
  useFeed.setMetadata((metadata) => ({ ...metadata, requests: metadata.requests + 1 }));

  return useFeed.metadata.requests;
}

Read it with store.metadata (a live getter) or store.getMetadata(), and change it with store.setMetadata(valueOrUpdater). Actions receive metadata, getMetadata and setMetadata too.

Documentation
↑↓ Navigate ↵ Open Esc CloseRGSH docs
Get started

Shared state. Precise subscriptions.
Built-in DevTools.