Rxova
Skip to content

useSharedStore

function useSharedStore<S, T>(selector, options?): T;

Read a derived value from a shared store, re-rendering only when it changes.

useSharedState subscribes to one key, which is the right shape for reading one thing. Reading across keys meant either one hook per key or a subscription to the whole store, and the latter re-renders on every write to anything in it.

const total = useSharedStore<Cart, number>(
(cart) => cart.items.length + cart.saved.length,
);

The selector runs on every store change; the component only re-renders when its result changes by equal.

useSharedState(key, initial) registers key with a default. A selector does not — it sees whatever is in the store, so a key nothing has registered or written yet is undefined. Write selectors that tolerate that, or declare the defaults with useSharedState (or a store initial) somewhere that mounts first.

The same applies on a server, where the store is inert and empty: the selector runs against {}, and its result is what the server-rendered markup shows.

Type Parameter
S extends Record<string, unknown>
T
ParameterType
selector(state) => T
options?UseSharedSelectorOptions

T