Start
Core Concepts
A quick conceptual tour of state containers, the registry, instance modes, dependency tracking, and plugins.
One short section per idea: enough to make good decisions about how to structure state. The Mental Model has the deeper reasoning behind each one.
State Containers
A state container is a class that holds a typed state value and notifies listeners when it changes.
Each one covers one concern. An AuthCubit holds auth state, a CartCubit holds cart state, and each has its own state type, methods and lifecycle.
Cubit is the concrete class you’ll extend. It gives you three ways to change state:
class AuthCubit extends Cubit<{ user: User | null; loading: boolean }> { constructor() { super({ user: null, loading: false }); // initial state }
login = async (credentials: Credentials) => { this.patch({ loading: true }); // merge partial changes const user = await api.login(credentials); this.emit({ user, loading: false }); // replace entire state };
logout = () => { this.update((s) => ({ ...s, user: null })); // derive from current };}State containers don’t depend on React. A test can construct one, call methods and check state directly, with no DOM, hooks or providers.
Registry
The registry is a global singleton that holds state container instances. When two components call useBloc(CounterCubit), the registry gives both the same instance.
It maps each class (and optional instance key) to a single instance, plus a ref count tracking how many consumers are using it:
Registry├── CounterCubit (default) → instance, refCount: 2 ← two components├── AuthCubit (default) → instance, refCount: 1└── EditorCubit ("doc-42") → instance, refCount: 3Ref counting
Each useBloc increments the ref count on mount and decrements it on unmount. When the count reaches zero, the instance is disposed: its resources are cleaned up and it leaves the registry. Unused containers don’t pile up.
If you want an instance to survive even when nothing is using it, mark it with @blac({ keepAlive: true }).
Registry functions
In React, useBloc handles the registry for you. Outside React (tests, scripts, server-side), you interact with it directly. The headline verbs:
| Function | Creates? | Ref count | Use when |
|---|---|---|---|
acquire(Class) | Yes | +1 | You own this reference (must release later) |
ensure(Class) | Yes | No change | You need the instance but don’t own a reference |
borrow(Class) | No | No change | Instance must already exist (throws if not) |
release(Class) | No | -1 | Done with your reference |
This is the quick version. The complete function table (including borrowSafe, getRefCount, clear, and the keying rules) lives in Instance Management.
Instance Modes
Shared (default)
All calls to useBloc(CounterCubit) return the same instance. This is the common case for app-wide state like auth, theme, or cart.
Named
Put the distinguishing value in args (and select it with static key) to get a distinct instance per key. Different args resolve to different instances.
useBloc(EditorCubit, { args: { docId: 'doc-42' } });Isolated (per-mount)
With @blac({ isolated: true }), every useBloc mount gets its own private instance that is disposed when that component unmounts.
Keep alive
With @blac({ keepAlive: true }), the instance survives even when all components using it unmount. It persists for the lifetime of the app.
Inputs: args and deps
Components often need a container seeded with data. BlaC keeps that data in two separate lanes, so a shared instance with many consumers never gets conflicting input:
args— serializable data that identifies an instance (e.g. a document id). Same args resolve to the same instance; identity is derived from args alone.deps— non-serializable handles (callbacks, services) injected per consumer, never used for identity.
This is just the teaser; the full model, the precedence rules, and the failure modes live in Inputs.
Dependency Tracking
useBloc returns state wrapped in a proxy that records which values the component reads during render. Dependency Tracking has the full mechanism and edge cases.
function UserName() { const [state] = useBloc(UserCubit); return <span>{state.name}</span>; // only 'name' is tracked}If state.email changes and state.name doesn’t, this component doesn’t re-render. You don’t write a selector for this. (A re-render of the parent still re-renders it, as in any React component.)
See it live: CountReader tracks state.count; LabelReader tracks state.label. Each component’s render badge increments only when its own field changes.
Two components share one bloc. Each reads a different field. Change one — only its reader re-renders.
reads: state.count
reads: state.label
The tracking also works for:
- Nested properties:
state.user.profile.name(records the leaf path) - Array access:
state.items.length,state.items[0]
Getter reads participate too: the bloc returned by useBloc is proxied, so reading bloc.total during render records the this.state paths the getter touches. Use select when you want a getter’s return value, rather than its source paths, to decide re-renders. See Dependency Tracking.
There are two tracking modes, chosen by whether you pass a select option — there is no separate on/off flag:
| Mode | How | Best for |
|---|---|---|
| Auto-tracking (default) | Proxy records property access during render | Most components |
select (manual) | You return an array; re-render when it changes per-index | Complex conditions or computed values |
A component that only calls methods and never displays state needs no special option: do not read from state, and auto-tracking records nothing to wake it. See Dependency Tracking for the full story, including the conditional-read caveat.
Plugins
Plugins observe lifecycle events across all state containers. They receive callbacks for instance creation, state changes, and disposal.
const plugin: BlacPlugin = { name: 'my-plugin', version: '1.0.0', onStateChange(ctx, prev, next, paths) { ... },};
getPluginManager().install(plugin);Official plugins: Logging, DevTools, Persistence.
Glossary
| Term | Meaning |
|---|---|
Cubit | The concrete class you subclass to hold typed state, actions (methods), and derived state (getters). |
StateContainer | The abstract base class underneath Cubit. Cubit makes emit, update, and patch public; StateContainer keeps them protected. |
| Bloc | Colloquial shorthand in the docs and hooks (useBloc) for any Cubit or StateContainer instance. (There is no separate Bloc class.) |
| Registry | The global singleton (StateContainerRegistry) that creates, shares, ref-counts, and disposes container instances. |
args | Serializable construction data passed via { args } that both keys the instance identity and runs init(args) before the first render. |
deps | Non-serializable per-consumer handles (DOM refs, controller instances) contributed via useBlocDeps and read lazily on this.deps. Never affects instance identity. |
| Auto-tracking | The default useBloc mode: a render-time Proxy records every leaf property path read during render and wakes the component only when one of those paths changes. |
select | An optional callback on useBloc (select: (state, bloc) => [...]) that opts out of auto-tracking and re-renders only when the returned array changes per-index (Object.is). |
isolated | Class option (@blac({ isolated: true })) that gives each useBloc mount its own private instance instead of sharing. |
keepAlive | Class option (@blac({ keepAlive: true })) that prevents auto-disposal when an instance’s ref count drops to zero. |
| Plugin | An object implementing BlacPlugin installed on getPluginManager() to observe creation, state changes, hydration, and disposal across all instances. |
Next
- Inputs:
args,depsand instance identity in full. - Instance Management: every registry function.
- Dependency Tracking: tracking in depth.
- Mental Model: the reasoning behind this page.