Skip to main content

Store

For several reasons (such as SSR), it's not a good idea for Stan to keep state locally. Instead, it uses a central store: every change is written to the store, and every value is read from it. However, the store-oriented design introduces some semantic overhead in the form of the Scoped<T> type.

Scoped<T>

Rather than directly producing state, all Stan primitives (atom, selector, etc.) output memoized functions that map from Store to state:

type Scoped<T extends State<any>> = (store: Store) => T;

That way, every piece of state is "scoped" to a specific Store instance. A change in the context of store A doesn't exist in the context of store B, and vice versa:

const myAtom = atom(42);

myAtom(storeA).get(); // 42

myAtom(storeA).set(prev => prev + 1);

myAtom(storeB).get(); // 42
info

Manually providing a Store instance is only necessary when working with vanilla Stan. Framework bindings (like those for React) handle this automatically, hiding the complexity entirely.

The Store class

While the Store class should be treated as opaque and its internals as implementation details, there may be situations where instantiating it is necessary. Stan provides several ways to do this:

  • Manual: new Store()
  • Using the makeStore() helper
  • DEFAULT_STORE, the default instance used when working with React

See also