blac

    Start

    Quick Start

    Install BlaC, write a Cubit, use it from React, share it between components and load data. About ten minutes.

    Installation

    Terminal window
    pnpm add @blac/core @blac/react
    Terminal window
    npm install @blac/core @blac/react
    Terminal window
    yarn add @blac/core @blac/react

    BlaC needs React 18 or 19. TypeScript is optional, but recommended: state and method types flow from your class into useBloc.

    Recommended tsconfig.json

    A standard strict React setup works. The @blac(...) decorator (for options like keepAlive and isolated) works as a legacy (experimentalDecorators) or a TC39 decorator. To skip decorators, call it as a function instead: blac({ keepAlive: true })(MyCubit), which needs no compiler flags.

    {
    "compilerOptions": {
    "target": "ESNext",
    "jsx": "react-jsx",
    "strict": true,
    "useDefineForClassFields": true,
    "experimentalDecorators": true, // only if you use @blac(...) decorator syntax
    },
    }

    Step 1: Define a Cubit

    A Cubit is a class that holds state and has methods that change it.

    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';
    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 });
    CounterCubit.decrement: () => void
    decrement
    = () => this.
    Cubit<{ count: number; }, void, Record<string, never>>.update(fn: (state: {
    count: number;
    }) => {
    count: number;
    }): void
    update
    ((
    s: {
    count: number;
    }
    s
    ) => ({
    count: number
    count
    :
    s: {
    count: number;
    }
    s
    .
    count: number
    count
    - 1 }));
    CounterCubit.reset: () => void
    reset
    = () => this.
    Cubit<{ count: number; }, void, Record<string, never>>.patch(partial: {
    count?: number | undefined;
    }): void

    super.patch merges and calls emit, so only the warning differs.

    patch
    ({
    count?: number | undefined
    count
    : 0 });
    }

    Three ways to change state:

    MethodWhat it doesWhen to use
    emit(newState)Replace the entire stateYou have the full new state ready
    update(fn)Derive new state from currentYou need to read current state first
    patch(partial)Deep-merge partial changes (DeepPartial<S>)You want to update some fields and keep the rest

    Step 2: Use it in React

    useBloc connects a component to a Cubit.

    import { useBloc } from '@blac/react';
    function Counter() {
    const [state, counter] = useBloc(CounterCubit);
    return (
    <div>
    <p>Count: {state.count}</p>
    <button onClick={counter.increment}>+</button>
    <button onClick={counter.decrement}>-</button>
    <button onClick={counter.reset}>Reset</button>
    </div>
    );
    }

    useBloc returns a tuple:

    • state: the current state. The values the component reads from it decide when it re-renders.
    • counter: the Cubit instance. Call its methods.

    Step 3: Share state across components

    Every component that calls useBloc(CounterCubit) gets the same instance, so state is shared by default.

    function CounterDisplay() {
    const [state] = useBloc(CounterCubit);
    return <p>Count: {state.count}</p>;
    }
    function CounterControls() {
    const [, counter] = useBloc(CounterCubit);
    return <button onClick={counter.increment}>+</button>;
    }
    function App() {
    return (
    <>
    <CounterDisplay />
    <CounterControls />
    </>
    );
    }

    When CounterControls calls increment, CounterDisplay re-renders with the new count. CounterControls never reads state, so it doesn’t re-render at all. No provider, context or prop drilling is involved.

    Step 4: Add business logic

    Rules belong in the class. The component stays a view.

    class TodoCubit extends Cubit<{ items: string[]; input: string }> {
    constructor() {
    super({ items: [], input: '' });
    }
    setInput = (value: string) => this.patch({ input: value });
    addTodo = () => {
    const trimmed = this.state.input.trim();
    if (!trimmed) return;
    // emit/update REPLACE state, so list every key you want to keep.
    this.update((s) => ({ items: [...s.items, trimmed], input: '' }));
    };
    removeTodo = (index: number) => {
    // patch deep-merges, so we only mention the key we change.
    this.patch({ items: this.state.items.filter((_, i) => i !== index) });
    };
    get isEmpty() {
    return this.state.items.length === 0;
    }
    }

    Notice the two write styles: addTodo uses update and lists both keys (replacing the whole state), while removeTodo uses patch and mentions only items (merging into the rest). Both are correct — the difference is exactly the replace-vs-merge rule from Step 1.

    Getters like isEmpty compute their value on every read, so they can’t drift from items. When a component reads todo.isEmpty during render, tracking records what the getter read (items.length), and the component re-renders when that changes. Dependency Tracking has the full rules.

    Step 5: Fetch something

    An async action is a method that awaits and updates state as it goes. Model the lifecycle as a status union so the view can render loading and error states, and guard with a request id so a slow response can’t overwrite a newer one.

    type
    type UserState = {
    status: "idle";
    } | {
    status: "loading";
    } | {
    status: "success";
    user: User;
    } | {
    status: "error";
    message: string;
    }
    UserState
    =
    | {
    status: "idle"
    status
    : 'idle' }
    | {
    status: "loading"
    status
    : 'loading' }
    | {
    status: "success"
    status
    : 'success';
    user: User
    user
    :
    interface User
    User
    }
    | {
    status: "error"
    status
    : 'error';
    message: string
    message
    : string };
    class
    class UserCubit
    UserCubit
    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
    <
    type UserState = {
    status: "idle";
    } | {
    status: "loading";
    } | {
    status: "success";
    user: User;
    } | {
    status: "error";
    message: string;
    }
    UserState
    > {
    private
    UserCubit.requestId: number
    requestId
    = 0;
    constructor() {
    super({
    status: "idle"
    status
    : 'idle' });
    }
    UserCubit.load: (id: string) => Promise<void>
    load
    = async (
    id: string
    id
    : string) => {
    const
    const reqId: number
    reqId
    = ++this.
    UserCubit.requestId: number
    requestId
    ; // claim the latest slot
    this.
    Cubit<UserState, void, Record<string, never>>.emit(next: UserState): void
    emit
    ({
    status: "loading"
    status
    : 'loading' });
    try {
    const
    const user: User
    user
    = await
    const api: {
    fetchUser(id: string): Promise<User>;
    }
    api
    .
    function fetchUser(id: string): Promise<User>
    fetchUser
    (
    id: string
    id
    );
    if (
    const reqId: number
    reqId
    !== this.
    UserCubit.requestId: number
    requestId
    ) return; // a newer call won; bail
    this.
    Cubit<UserState, void, Record<string, never>>.emit(next: UserState): void
    emit
    ({
    status: "success"
    status
    : 'success',
    user: User
    user
    });
    } catch (
    function (local var) e: unknown
    e
    ) {
    if (
    const reqId: number
    reqId
    !== this.
    UserCubit.requestId: number
    requestId
    ) return;
    this.
    Cubit<UserState, void, Record<string, never>>.emit(next: UserState): void
    emit
    ({
    status: "error"
    status
    : 'error',
    message: string
    message
    :
    var String: StringConstructor
    (value?: any) => string

    Allows manipulation and formatting of text strings and determination and location of substrings within strings.

    String
    (
    function (local var) e: unknown
    e
    ) });
    }
    };
    }

    The view switches on state.status, and TypeScript narrows each branch. For real apps, @blac/async packages this pattern: a status slot in state, the latest request wins, and requests abort when the bloc is released. The Async guide covers cancellation and why BlaC doesn’t use Suspense.

    What just happened?

    When you call useBloc(CounterCubit):

    1. The registry looks for an existing CounterCubit instance, and creates one if there is none.
    2. It increments the instance’s ref count: how many components are using it.
    3. During render, state is a proxy that records which values the component reads.
    4. When state changes, the component re-renders only if one of the values it read changed.
    5. On unmount, the ref count goes down. At zero, the instance is disposed.

    The Mental Model explains why each step works this way: why a proxy instead of selectors, why disposal is automatic, why updates batch on a microtask.

    Next