blac

    Start

    What is BlaC?

    An overview of BlaC: what it does, its packages, how it compares to other libraries, and when to use it.

    Watch it run: Chapter 01 · Touch it, you're subscribed.

    BlaC (Business Logic Components) is a state management library for React and TypeScript. You write state, and the logic that changes it, as plain classes called Cubits. Components use them through one hook, useBloc.

    import
    (alias) namespace React
    import React
    React
    from 'react';
    import {
    class Cubit<S extends object = any, Args = void, Deps extends object = Record<string, never>>

    Cubit<S> is a StateContainer<S> that exposes mutation publicly.

    That is the whole difference, and it is a real one: on StateContainer emit / patch / update are protected, so a container mutates itself from its own methods and callers go through the API it chooses to publish. Cubit re-declares the three as public for the cases where a caller legitimately drives state from outside — test helpers, devtools time-travel, benchmarks.

    Reach for StateContainer when business logic should live in the class, and Cubit when the caller owns the transitions.

    Cubit
    } from '@blac/core';
    import {
    function useBloc<T extends StateContainerConstructor = StateContainerConstructor>(BlocClass: T, options?: UseBlocOptions<T>): UseBlocReturn<T, ExtractState<T>>

    React hook that connects a component to a state container with automatic re-render on state changes.

    Two tracking modes:

    • Auto-tracking (default): the returned state value is a proxy that records read paths during render. The component re-renders when any recorded path changes.
    • Manual select: pass options.select to opt out of auto-tracking. The hook re-renders only when the returned array's elements change (per-index Object.is).

    Lifecycle:

    • The bloc is acquired from the registry on mount and released at the end of the tick in which the component unmounts, so a consumer mounting in the same commit takes over the instance instead of getting a new one. The instance key is derived from options.args (own args), then the surrounding

    BlocProvider

    context args for this bloc, then the default key (no args).

    • If the bloc is disposed from outside while mounted (clear, clearWhere, ...), the component re-renders against a new instance.
    • options.onMount fires after the bloc is acquired; options.onUnmount fires before the registry releases its ref, so the bloc is still alive when the callback runs.

    Per-mount private instance: mark the class @blac({ isolated: true }), or pass a unique key arg yourself (e.g. useId() in args). A per-mount instance does not survive a first render that suspends: React discards that render's hook state, so the retry gets a new instance. Do not use() a promise owned by a per-mount bloc in the component that creates it.

    @typeParam ― T - The state container constructor type (inferred from BlocClass)

    @param ― BlocClass - The state container class to connect to

    @param ― options - Configuration options

    @returns ― Tuple of [state, bloc]

    @example

    Basic usage

    const [state, bloc] = useBloc(MyBloc);

    @example

    Manual select

    const [state, bloc] = useBloc(MyBloc, {
    select: (state) => [state.count],
    });

    @example

    Args-based shared instance

    const [state, bloc] = useBloc(UserBloc, { args: { userId: 'alice' } });

    @public

    useBloc
    } from '@blac/react';
    class
    class CounterCubit
    CounterCubit
    extends
    class Cubit<S extends object = any, Args = void, Deps extends object = Record<string, never>>

    Cubit<S> is a StateContainer<S> that exposes mutation publicly.

    That is the whole difference, and it is a real one: on StateContainer emit / patch / update are protected, so a container mutates itself from its own methods and callers go through the API it chooses to publish. Cubit re-declares the three as public for the cases where a caller legitimately drives state from outside — test helpers, devtools time-travel, benchmarks.

    Reach for StateContainer when business logic should live in the class, and Cubit when the caller owns the transitions.

    Cubit
    <{
    count: number
    count
    : number }> {
    constructor() {
    super({
    count: number
    count
    : 0 });
    }
    CounterCubit.increment: () => void
    increment
    = () => this.
    Cubit<{ count: number; }, void, Record<string, never>>.emit(next: {
    count: number;
    }): void
    emit
    ({
    count: number
    count
    : this.
    StateContainer<{ count: number; }, void, Record<string, never>>.state: {
    count: number;
    }
    state
    .
    count: number
    count
    + 1 });
    }
    function
    function Counter(): JSX.Element
    Counter
    () {
    const [
    const state: {
    readonly count: number;
    }
    state
    ,
    const counter: InstanceReadonlyState<typeof CounterCubit>
    counter
    ] =
    useBloc<typeof CounterCubit>(BlocClass: typeof CounterCubit, options?: UseBlocOptions<typeof CounterCubit> | undefined): UseBlocReturn<typeof CounterCubit, {
    readonly count: number;
    }>

    React hook that connects a component to a state container with automatic re-render on state changes.

    Two tracking modes:

    • Auto-tracking (default): the returned state value is a proxy that records read paths during render. The component re-renders when any recorded path changes.
    • Manual select: pass options.select to opt out of auto-tracking. The hook re-renders only when the returned array's elements change (per-index Object.is).

    Lifecycle:

    • The bloc is acquired from the registry on mount and released at the end of the tick in which the component unmounts, so a consumer mounting in the same commit takes over the instance instead of getting a new one. The instance key is derived from options.args (own args), then the surrounding

    BlocProvider

    context args for this bloc, then the default key (no args).

    • If the bloc is disposed from outside while mounted (clear, clearWhere, ...), the component re-renders against a new instance.
    • options.onMount fires after the bloc is acquired; options.onUnmount fires before the registry releases its ref, so the bloc is still alive when the callback runs.

    Per-mount private instance: mark the class @blac({ isolated: true }), or pass a unique key arg yourself (e.g. useId() in args). A per-mount instance does not survive a first render that suspends: React discards that render's hook state, so the retry gets a new instance. Do not use() a promise owned by a per-mount bloc in the component that creates it.

    @typeParam ― T - The state container constructor type (inferred from BlocClass)

    @param ― BlocClass - The state container class to connect to

    @param ― options - Configuration options

    @returns ― Tuple of [state, bloc]

    @example

    Basic usage

    const [state, bloc] = useBloc(MyBloc);

    @example

    Manual select

    const [state, bloc] = useBloc(MyBloc, {
    select: (state) => [state.count],
    });

    @example

    Args-based shared instance

    const [state, bloc] = useBloc(UserBloc, { args: { userId: 'alice' } });

    @public

    useBloc
    (
    class CounterCubit
    CounterCubit
    );
    return <
    React.JSX.IntrinsicElements.button: React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>
    button
    React.DOMAttributes<HTMLButtonElement>.onClick?: React.MouseEventHandler<HTMLButtonElement> | undefined
    onClick
    ={
    const counter: InstanceReadonlyState<typeof CounterCubit>
    counter
    .
    CounterCubit.increment: () => void
    increment
    }>Count: {
    const state: {
    readonly count: number;
    }
    state
    .
    count: number
    count
    }</
    React.JSX.IntrinsicElements.button: React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>
    button
    >;
    }

    That is the whole setup. There is no store to configure, no provider to wrap the app in, and no reducer or selector to write.

    What it does for you

    Keeps logic out of components. A Cubit holds state, derived values (getters), validation and async work. It has no React dependency, so it runs in a plain unit test and can be reused outside React. Components render state and call methods. Architecture & Philosophy explains why this split pays off.

    Re-renders only what read the change. During render, useBloc hands the component a proxy that records which values it reads. The component re-renders when one of those values changes, and other state changes never reach it. Below, two components share one Cubit and each reads a different field. Change a field and watch which render count moves:

    Re-render isolation — live demo

    Two components share one bloc. Each reads a different field. Change one — only its reader re-renders.

    CountReaderrenders1

    reads: state.count

    0
    LabelReaderrenders1

    reads: state.label

    Manages instances. A registry creates a Cubit the first time a component asks for it, shares it with every other component that asks, and disposes it when the last one unmounts. Pass args for one instance per key, mark a class isolated for one instance per mount, or keepAlive to keep it after the last unmount.

    Types flow through. State, methods and args are typed from the class itself, so useBloc needs no type annotations.

    Packages

    PackageWhat it gives you
    @blac/coreCubit, the registry, watch(), cross-bloc tracking, plugins. No React.
    @blac/reactuseBloc, BlocProvider, RegistryProvider, and testing helpers.
    @blac/asyncresource(), mutation() and tag-based invalidate(), kept in state.
    @blac/plugin-persistPersist state to IndexedDB or Web Storage.
    @blac/devtools-*An in-app panel and a Chrome DevTools extension.
    @blac/logging-pluginStructured logs of state changes.
    Under the hood: DirtyTalk

    The change tracking (path-based dirty tracking, the render-time proxy, batched flushing) lives in a lower-level, framework-agnostic family of packages called DirtyTalk. BlaC’s StateContainer extends @dirtytalk/structural’s container. You never need to use it directly.

    How it compares

    LibraryWhere logic livesWhat decides re-rendersLifecycle and sharing
    BlaCTyped Cubit classesValues read during render, recorded by a proxyRef-counted registry: shared, keyed, isolated or kept alive
    ZustandStore creator functionA selector per hook (useStore(s => s.x))Module singleton, or a store in context
    Redux ToolkitSlices, reducers, thunksuseSelector, often with createSelectorOne global store in <Provider>
    MobXObservable classesObservables read inside observer()You create instances; share them through context
    JotaiSmall composed atomsA subscription per atomProvider, or the default store

    Mental Model has the longer comparison, including when another library is the better fit.

    When to use it

    BlaC fits when:

    • State is shared by several components, without prop drilling or provider trees.
    • There is real business logic, such as validation, multi-step flows or derived values, that belongs in a testable class rather than spread across hooks.
    • You want fast unit tests of that logic, without mounting React.

    Next