blac

    Start

    Architecture & Philosophy

    Why BlaC exists. Splitting UI, Logic and Data keeps components focused on rendering, logic testable without a DOM, and data sources replaceable.

    Components tend to grow. One starts out rendering a button, and a few features later it holds useState, three useEffects, a fetch, validation rules and a loading flag, all before the return (.

    BlaC is built on one premise: components shouldn’t own business logic, and business logic shouldn’t depend on the UI framework.

    The problem with “fat components”

    When state, logic and data fetching all live in components and custom hooks:

    • Components do too many jobs. Besides turning state into markup, they orchestrate async flows, guard against stale closures and compute derived flags.
    • Re-renders become your job. useMemo, useCallback and hand-written selectors spread through the code to keep unrelated views from re-rendering.
    • Testing needs a DOM. Checking a validation rule or a checkout flow means mounting a component tree, mocking providers and clicking simulated buttons.
    • The logic is tied to the view library. Reusing a feature in React Native or a script means untangling it from hooks first.

    Three layers: UI, Logic and Data

    BlaC splits an application into three layers, each with one job:

    1. The UI Layer

    Renders state and forwards interactions. Components turn state into markup and call methods from onClick, onChange or onSubmit. They never talk to the Data layer directly.

    2. The Logic Layer (The Core)

    Where the application lives. Cubit classes hold state, validate input, derive values, coordinate features and call the Data layer. They don’t depend on React or the DOM.

    3. The Data Layer

    Moves data in and out. REST, GraphQL, IndexedDB, localStorage or an in-memory fake for tests. The Logic layer doesn’t care how data is stored, and the UI doesn’t know this layer exists.

    The one-way rule: UI never touches Data

    The boundary that matters most: nothing travels between UI and Data without passing through the Logic layer. Components call methods; methods call the API; state flows back to the components that read it.

    Here is a checkout flow split that way:

    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';
    interface
    interface OrderItem
    OrderItem
    {
    OrderItem.id: string
    id
    : string;
    OrderItem.price: number
    price
    : number;
    OrderItem.qty: number
    qty
    : number;
    }
    // ── 3. DATA LAYER: plain functions or clients (REST, GraphQL, memory) ──
    const
    const orderApi: {
    submitOrder(items: OrderItem[]): Promise<{
    orderId: string;
    }>;
    }
    orderApi
    = {
    async
    function submitOrder(items: OrderItem[]): Promise<{
    orderId: string;
    }>
    submitOrder
    (
    items: OrderItem[]
    items
    :
    interface OrderItem
    OrderItem
    []):
    interface Promise<T>

    Represents the completion of an asynchronous operation

    Promise
    <{
    orderId: string
    orderId
    : string }> {
    return {
    orderId: string
    orderId
    : 'ord_123' };
    },
    };
    // ── 2. LOGIC LAYER: pure TypeScript class, zero React imports ──
    interface
    interface CheckoutState
    CheckoutState
    {
    CheckoutState.items: OrderItem[]
    items
    :
    interface OrderItem
    OrderItem
    [];
    CheckoutState.status: "idle" | "submitting" | "confirmed" | "error"
    status
    : 'idle' | 'submitting' | 'confirmed' | 'error';
    CheckoutState.orderId: string | null
    orderId
    : string | null;
    }
    export class
    class CheckoutCubit
    CheckoutCubit
    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
    <
    interface CheckoutState
    CheckoutState
    > {
    constructor(private
    CheckoutCubit.api: {
    submitOrder(items: OrderItem[]): Promise<{
    orderId: string;
    }>;
    }
    api
    =
    const orderApi: {
    submitOrder(items: OrderItem[]): Promise<{
    orderId: string;
    }>;
    }
    orderApi
    ) {
    super({
    CheckoutState.items: OrderItem[]
    items
    : [],
    CheckoutState.status: "idle" | "submitting" | "confirmed" | "error"
    status
    : 'idle',
    CheckoutState.orderId: string | null
    orderId
    : null });
    }
    get
    CheckoutCubit.total: number
    total
    (): number {
    return this.
    StateContainer<CheckoutState, void, Record<string, never>>.state: CheckoutState
    state
    .
    CheckoutState.items: OrderItem[]
    items
    .
    Array<OrderItem>.reduce<number>(callbackfn: (previousValue: number, currentValue: OrderItem, currentIndex: number, array: OrderItem[]) => number, initialValue: number): number (+2 overloads)

    Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

    @param ― callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.

    @param ― initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

    reduce
    ((
    sum: number
    sum
    ,
    i: OrderItem
    i
    ) =>
    sum: number
    sum
    +
    i: OrderItem
    i
    .
    OrderItem.price: number
    price
    *
    i: OrderItem
    i
    .
    OrderItem.qty: number
    qty
    , 0);
    }
    get
    CheckoutCubit.canSubmit: boolean
    canSubmit
    (): boolean {
    return this.
    StateContainer<CheckoutState, void, Record<string, never>>.state: CheckoutState
    state
    .
    CheckoutState.items: OrderItem[]
    items
    .
    Array<OrderItem>.length: number

    Gets or sets the length of the array. This is a number one higher than the highest index in the array.

    length
    > 0 && this.
    StateContainer<CheckoutState, void, Record<string, never>>.state: CheckoutState
    state
    .
    CheckoutState.status: "idle" | "submitting" | "confirmed" | "error"
    status
    !== 'submitting';
    }
    CheckoutCubit.submit: () => Promise<void>
    submit
    = async () => {
    if (!this.
    CheckoutCubit.canSubmit: boolean
    canSubmit
    ) return;
    this.
    Cubit<CheckoutState, void, Record<string, never>>.patch(partial: {
    items?: readonly {
    id?: string | undefined;
    price?: number | undefined;
    qty?: number | undefined;
    }[] | undefined;
    status?: "idle" | "submitting" | "confirmed" | "error" | undefined;
    orderId?: string | null | undefined;
    }): void

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

    patch
    ({
    status?: "idle" | "submitting" | "confirmed" | "error" | undefined
    status
    : 'submitting' });
    try {
    const {
    const orderId: string
    orderId
    } = await this.
    CheckoutCubit.api: {
    submitOrder(items: OrderItem[]): Promise<{
    orderId: string;
    }>;
    }
    api
    .
    function submitOrder(items: OrderItem[]): Promise<{
    orderId: string;
    }>
    submitOrder
    (this.
    StateContainer<CheckoutState, void, Record<string, never>>.state: CheckoutState
    state
    .
    CheckoutState.items: OrderItem[]
    items
    );
    this.
    Cubit<CheckoutState, void, Record<string, never>>.patch(partial: {
    items?: readonly {
    id?: string | undefined;
    price?: number | undefined;
    qty?: number | undefined;
    }[] | undefined;
    status?: "idle" | "submitting" | "confirmed" | "error" | undefined;
    orderId?: string | null | undefined;
    }): void

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

    patch
    ({
    status?: "idle" | "submitting" | "confirmed" | "error" | undefined
    status
    : 'confirmed',
    orderId?: string | null | undefined
    orderId
    ,
    items?: readonly {
    id?: string | undefined;
    price?: number | undefined;
    qty?: number | undefined;
    }[] | undefined
    items
    : [] });
    } catch {
    this.
    Cubit<CheckoutState, void, Record<string, never>>.patch(partial: {
    items?: readonly {
    id?: string | undefined;
    price?: number | undefined;
    qty?: number | undefined;
    }[] | undefined;
    status?: "idle" | "submitting" | "confirmed" | "error" | undefined;
    orderId?: string | null | undefined;
    }): void

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

    patch
    ({
    status?: "idle" | "submitting" | "confirmed" | "error" | undefined
    status
    : 'error' });
    }
    };
    }
    // ── 1. UI LAYER: takes state, renders markup, wires callbacks ──
    export function
    function CheckoutSummary(): JSX.Element
    CheckoutSummary
    () {
    const [
    const state: {
    readonly items: readonly {
    readonly id: string;
    readonly price: number;
    readonly qty: number;
    }[];
    readonly status: "idle" | "submitting" | "confirmed" | "error";
    readonly orderId: string | null;
    }
    state
    ,
    const checkout: InstanceReadonlyState<typeof CheckoutCubit>
    checkout
    ] =
    useBloc<typeof CheckoutCubit>(BlocClass: typeof CheckoutCubit, options?: UseBlocOptions<typeof CheckoutCubit> | undefined): UseBlocReturn<typeof CheckoutCubit, {
    readonly items: readonly {
    readonly id: string;
    readonly price: number;
    readonly qty: number;
    }[];
    readonly status: "idle" | "submitting" | "confirmed" | "error";
    readonly orderId: string | null;
    }>

    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 CheckoutCubit
    CheckoutCubit
    );
    return (
    <
    React.JSX.IntrinsicElements.section: React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement>
    section
    >
    <
    React.JSX.IntrinsicElements.p: React.DetailedHTMLProps<React.HTMLAttributes<HTMLParagraphElement>, HTMLParagraphElement>
    p
    >Total: ${
    const checkout: InstanceReadonlyState<typeof CheckoutCubit>
    checkout
    .
    CheckoutCubit.total: number
    total
    .
    Number.toFixed(fractionDigits?: number): string

    Returns a string representing a number in fixed-point notation.

    @param ― fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive.

    toFixed
    (2)}</
    React.JSX.IntrinsicElements.p: React.DetailedHTMLProps<React.HTMLAttributes<HTMLParagraphElement>, HTMLParagraphElement>
    p
    >
    <
    React.JSX.IntrinsicElements.button: React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>
    button
    React.ButtonHTMLAttributes<HTMLButtonElement>.disabled?: boolean | undefined
    disabled
    ={!
    const checkout: InstanceReadonlyState<typeof CheckoutCubit>
    checkout
    .
    CheckoutCubit.canSubmit: boolean
    canSubmit
    }
    React.DOMAttributes<HTMLButtonElement>.onClick?: React.MouseEventHandler<HTMLButtonElement> | undefined
    onClick
    ={
    const checkout: InstanceReadonlyState<typeof CheckoutCubit>
    checkout
    .
    CheckoutCubit.submit: () => Promise<void>
    submit
    }>
    {
    const state: {
    readonly items: readonly {
    readonly id: string;
    readonly price: number;
    readonly qty: number;
    }[];
    readonly status: "idle" | "submitting" | "confirmed" | "error";
    readonly orderId: string | null;
    }
    state
    .
    status: "idle" | "submitting" | "confirmed" | "error"
    status
    === 'submitting' ? 'Placing order…' : 'Place order'}
    </
    React.JSX.IntrinsicElements.button: React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>
    button
    >
    {
    const state: {
    readonly items: readonly {
    readonly id: string;
    readonly price: number;
    readonly qty: number;
    }[];
    readonly status: "idle" | "submitting" | "confirmed" | "error";
    readonly orderId: string | null;
    }
    state
    .
    orderId: string | null
    orderId
    && <
    React.JSX.IntrinsicElements.p: React.DetailedHTMLProps<React.HTMLAttributes<HTMLParagraphElement>, HTMLParagraphElement>
    p
    >Order #{
    const state: {
    readonly items: readonly {
    readonly id: string;
    readonly price: number;
    readonly qty: number;
    }[];
    readonly status: "idle" | "submitting" | "confirmed" | "error";
    readonly orderId: string | null;
    }
    state
    .
    orderId: string
    orderId
    } confirmed!</
    React.JSX.IntrinsicElements.p: React.DetailedHTMLProps<React.HTMLAttributes<HTMLParagraphElement>, HTMLParagraphElement>
    p
    >}
    </
    React.JSX.IntrinsicElements.section: React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement>
    section
    >
    );
    }

    Look at CheckoutSummary at the bottom:

    • It has no business logic. It doesn’t compute the total, decide whether submitting is allowed, or handle network errors.
    • It has no selectors. The render-time proxy records that it read checkout.total, checkout.canSubmit, state.status and state.orderId, and re-renders it when one of those changes.
    • It knows how to render the current state and which method to call. Nothing else.

    Why this pays off

    1. The UI can change

    @blac/core has no React dependency, so a Cubit runs anywhere JavaScript does:

    • React and React Native: useBloc(CheckoutCubit), with the same class.
    • Scripts, servers and workers: drive the class with acquire() and watch(). See Using BlaC outside React.
    • Other view libraries: a small adapter around watch() connects them, and the Logic and Data layers stay as they are.

    2. The data source can change

    The Logic layer calls plain functions or interfaces, like orderApi above. Storage that applies to many blocs, such as IndexedDB or localStorage, attaches from outside as a plugin:

    • Prototype against an in-memory fake.
    • Switch to REST or GraphQL when the backend is ready, by changing the API module.
    • Add persistence with @blac/plugin-persist without changing components.

    3. Logic is tested without rendering

    When the logic lives in a class, a test constructs it, calls methods and checks state. No React tree, no act(), no simulated browser:

    // The whole checkout flow, tested without a DOM:
    const
    const fakeApi: {
    submitOrder: () => Promise<{
    orderId: string;
    }>;
    }
    fakeApi
    = {
    submitOrder: () => Promise<{
    orderId: string;
    }>
    submitOrder
    : async () => ({
    orderId: string
    orderId
    : 'test_99' }),
    };
    const
    const checkout: CheckoutCubit
    checkout
    = new
    constructor CheckoutCubit(api: {
    submitOrder(items: OrderItem[]): Promise<{
    orderId: string;
    }>;
    }): CheckoutCubit
    CheckoutCubit
    (
    const fakeApi: {
    submitOrder: () => Promise<{
    orderId: string;
    }>;
    }
    fakeApi
    );
    const checkout: CheckoutCubit
    checkout
    .
    Cubit<CheckoutState, void, Record<string, never>>.patch(partial: {
    items?: readonly {
    id?: string | undefined;
    price?: number | undefined;
    qty?: number | undefined;
    }[] | undefined;
    status?: "idle" | "submitting" | "confirmed" | "error" | undefined;
    orderId?: string | null | undefined;
    }): void

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

    patch
    ({
    items?: readonly {
    id?: string | undefined;
    price?: number | undefined;
    qty?: number | undefined;
    }[] | undefined
    items
    : [{
    id?: string | undefined
    id
    : '1',
    price?: number | undefined
    price
    : 25,
    qty?: number | undefined
    qty
    : 2 }] });
    var console: Console
    console
    .
    Console.assert(condition?: boolean, ...data: any[]): void

    The console.assert() static method writes an error message to the console if the assertion is false. If the assertion is true, nothing happens.

    MDN Reference

    assert
    (
    const checkout: CheckoutCubit
    checkout
    .
    CheckoutCubit.total: number
    total
    === 50);
    var console: Console
    console
    .
    Console.assert(condition?: boolean, ...data: any[]): void

    The console.assert() static method writes an error message to the console if the assertion is false. If the assertion is true, nothing happens.

    MDN Reference

    assert
    (
    const checkout: CheckoutCubit
    checkout
    .
    CheckoutCubit.canSubmit: boolean
    canSubmit
    === true);
    await
    const checkout: CheckoutCubit
    checkout
    .
    CheckoutCubit.submit: () => Promise<void>
    submit
    ();
    var console: Console
    console
    .
    Console.assert(condition?: boolean, ...data: any[]): void

    The console.assert() static method writes an error message to the console if the assertion is false. If the assertion is true, nothing happens.

    MDN Reference

    assert
    (
    const checkout: CheckoutCubit
    checkout
    .
    StateContainer<CheckoutState, void, Record<string, never>>.state: CheckoutState
    state
    .
    CheckoutState.status: "idle" | "submitting" | "confirmed" | "error"
    status
    === 'confirmed');
    var console: Console
    console
    .
    Console.assert(condition?: boolean, ...data: any[]): void

    The console.assert() static method writes an error message to the console if the assertion is false. If the assertion is true, nothing happens.

    MDN Reference

    assert
    (
    const checkout: CheckoutCubit
    checkout
    .
    StateContainer<CheckoutState, void, Record<string, never>>.state: CheckoutState
    state
    .
    CheckoutState.orderId: string | null
    orderId
    === 'test_99');

    When you do test a component, renderWithBloc mounts it with the state you choose, so you don’t mock fetch or replay user steps to reach that state.

    Pragmatism over dogma

    The three layers are a tool, not a rule:

    • Local UI state is fine. Whether a dropdown is open can stay in useState if nothing else cares.
    • No ceremony for small things. A feature doesn’t need interfaces, factories and three files. One Cubit next to the component already separates the logic and makes it testable.
    • Grow when it helps. Start with one Cubit. Later, move API calls into a data module, compose blocs with depend(), or use @blac/async for request cancellation and invalidation.

    Next