Stores and hooks
What createGlobalState returns, how the hook doubles as the store API, and why state lives outside React.
The problem this solves
Some state is not owned by one component: the signed-in user, a shopping cart, a theme. Passing it down through props or wrapping the app in providers couples every consumer to the tree. A store keeps that state at module scope, and any component can subscribe to it.
One call, one hook
createGlobalState(initialState, options?) returns a hook. Call it inside a component to subscribe.
import { createGlobalState } from 'react-global-state-hooks';
export const useCart = createGlobalState({ items: [] as string[] }, { metadata: { currency: 'USD' } });
export function CartSummary() {
// [state, setState, metadata]: the third item is the store's non-reactive metadata.
const [cart, setCart, metadata] = useCart();
return (
<button onClick={() => setCart((current) => ({ ...current, items: [...current.items, 'book'] }))}>
{cart.items.length} items ({metadata.currency})
</button>
);
}The hook returns a tuple:
| Position | Value |
|---|---|
| 0 | The state, or the result of your selector when you pass one. |
| 1 | A setState function, or the actions object when the store defines actions. |
| 2 | The store’s metadata. It is not reactive. |
The hook is also the store
The function you get back carries the whole store API, so the same import works inside and outside React.
| Member | What it does |
|---|---|
getState() | Current state. |
setState(valueOrUpdater) | Replace the state. Skipped when the new value is the same reference. |
subscribe(selector?, callback, options?) | Listen outside React. Returns an unsubscribe function. |
select(selector, deps?) | Like the hook, but returns only the selected value. |
createSelectorHook(selector, options?) | A reusable, shared derived hook. |
createObservable(selector, options?) | A subscribable slice of the state. |
metadata, getMetadata(), setMetadata() | Non-reactive side data. |
reset() | A test helper: restore the initial state (see Testing). |
dispose() | Remove subscriptions and run cleanup. |
actions | The actions object, when actions are configured. |
Initial state
Pass a value, or a function that returns one. Use the function form when the initial state should be created
fresh each time. It is also what lets a test restore the store with reset() (see Testing).
const useSession = createGlobalState(() => ({ user: null as string | null }));What to watch for
- Updating with the same reference does nothing. Return a new object or array.
- The tuple’s third item is the metadata object itself; changing metadata does not cause a render.