@blac/react
Version:
React bindings for BlaC — useBloc hook with automatic re-render optimization
54 lines (53 loc) • 2.09 kB
TypeScript
import { type ExtractState, type StateContainerConstructor } from '@blac/core';
import type { UseBlocOptions, UseBlocReturn } from './types';
/**
* 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. Backed by `@dirtytalk/structural`'s
* {@link trackRender} + the container's path-scoped `DirtyChannel`.
* - **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 on
* unmount. The instance key is derived from `options.args` (own args),
* then the surrounding {@link BlocProvider} context args for this bloc,
* then the default key (no args).
* - `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:
* ```ts
* const id = useId();
* const [state, bloc] = useBloc(MyBloc, { args: { _id: id } });
* ```
*
* @template 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, ref]`
*
* @example Basic usage
* ```ts
* const [state, bloc] = useBloc(MyBloc);
* ```
*
* @example Manual select
* ```ts
* const [state, bloc] = useBloc(MyBloc, {
* select: (state) => [state.count],
* });
* ```
*
* @example Args-based shared instance
* ```ts
* const [state, bloc] = useBloc(UserBloc, { args: { userId: 'alice' } });
* ```
*/
export declare function useBloc<T extends StateContainerConstructor = StateContainerConstructor>(BlocClass: T, options?: UseBlocOptions<T>): UseBlocReturn<T, ExtractState<T>>;