Skip to content
brix.v2.15.0+b120c49

Search documentation

Loading search…

    Documentation menu
    Docs / Pages and UIRead Markdown
    On this page

    Stores

    createStore provides request-safe SSR state and in-memory browser state shared across independently hydrated Preact islands. Use it when multiple islands on one page need the same reactive model. Keep state local with useSignal when only one component owns it; use storage when values must survive navigation, reloads, or browser tabs.

    Each island hydrates into a separate Preact tree, so ordinary context does not cross island roots. A store gives those trees one shared model, initialized from server-rendered provider props.

    Generate an application store

    #
    brix add store booking --feature booking
    

    The generator writes the store and a starter test:

    src/features/booking/
      booking.store.ts
      booking.store.test.ts
    

    Its createStore(() => ({})) placeholder has no state yet. Replace it with your model:

    src/features/booking/booking.store.ts
    import { useSignal } from "brix/hooks";
    import { createStore } from "brix/islands";
    
    export type Booking = { guestName: string; status: string };
    
    export const [BookingStoreProvider, useBookingStore] = createStore(
      ({ initialBooking }: { initialBooking: Booking }) => {
        const booking = useSignal(initialBooking);
        return {
          booking,
          confirm: () => {
            booking.value = { ...booking.value, status: "confirmed" };
          },
        };
      },
    );
    

    Discovery treats every module whose filename ends in .store.ts, .store.tsx, .store.js, or .store.jsx as a store. Name stores .store.ts: they render no JSX. A store module follows these rules, which discovery and brix build enforce:

    • The only runtime export is one exported array destructuring declaration of the tuple, exactly as above: export const [XStoreProvider, useXStore] = .... Type-only exports are allowed.
    • The tuple is created in the store module, by createStore or a factory call. Re-exporting a tuple imported from another module is rejected.
    • The provider name ends in StoreProvider, the hook name is use plus the same stem plus Store: BookingStoreProvider and useBookingStore.
    • Separate declarations, object destructuring, export lists, tuple holes, rest elements, and default bindings fail even if the exported names match.

    Brix gives each store a stable identity derived from its source path and provider name, so the server and every browser bundle agree on it. The key is injected into direct calls to the imported createStore, including calls wrapped in parentheses, as const, or satisfies, and namespace calls such as islands.createStore(...) after import * as islands from "brix/islands". An explicit second argument is preserved.

    Declare stores in the application that hydrates them. A shared library can export setup functions, domain operations, and types, but not a createStore tuple; doctor reports a tuple-exporting *.store.* module in a library. Generate the thin tuple in the owning application so its build discovers the provider.

    Render and consume the store

    #

    Generate an island for each consumer, such as brix add island BookingDetails --feature booking, and call the store hook inside it:

    src/features/booking/BookingDetails.tsx
    "use island";
    
    import { useBookingStore } from "./booking.store.ts";
    
    export function BookingDetails() {
      const store = useBookingStore();
      if (!store) return <p>Booking unavailable</p>;
    
      return (
        <div>
          <p>{store.booking.value.guestName}</p>
          <button type="button" onClick={store.confirm}>
            Confirm
          </button>
        </div>
      );
    }
    
    src/features/booking/BookingSummary.tsx
    "use island";
    
    import { useBookingStore } from "./booking.store.ts";
    
    export function BookingSummary() {
      const store = useBookingStore();
      return <p>Status: {store?.booking.value.status ?? "unknown"}</p>;
    }
    

    Place one provider above all consumers in the owning page component:

    src/features/booking/pages/bookingDetails/Page.tsx
    import { BookingDetails } from "#/features/booking/BookingDetails.tsx";
    import { BookingStoreProvider, type Booking } from "#/features/booking/booking.store.ts";
    import { BookingSummary } from "#/features/booking/BookingSummary.tsx";
    
    export function BookingDetailsPage({ booking }: { booking: Booking }) {
      return (
        <BookingStoreProvider initialBooking={booking}>
          <BookingDetails />
          <BookingSummary />
        </BookingStoreProvider>
      );
    }
    

    The initial HTML shows the guest and current status. Clicking Confirm in BookingDetails changes the status shown by BookingSummary, even though the two islands hydrate separately.

    The hook returns the setup result, or null when no provider state is available, so every consumer must handle null. In the browser the provider runs its setup without rendering its children: they remain server-rendered HTML, and any islands among them hydrate independently and read the published state. The provider therefore does not pull its children into its browser bundle.

    A non-island server component can also call the store hook during SSR when a provider is above it.

    Custom store factories

    #

    Discovery uses the *.store.ts filename, not the factory name, and Brix does not inject keys through factories. Put a reusable factory in an ordinary helper module and forward an explicit key:

    src/features/counters/create-counter-store.ts
    import { useSignal } from "brix/hooks";
    import { createStore } from "brix/islands";
    
    export function createCounterStore(initial: number, key: string) {
      return createStore(() => ({ count: useSignal(initial) }), key);
    }
    

    Each concrete store still has its own store module:

    src/features/counters/cart-count.store.ts
    import { createCounterStore } from "./create-counter-store.ts";
    
    export const [CartCountStoreProvider, useCartCountStore] = createCounterStore(0, "cart-count");
    
    src/features/counters/notification-count.store.ts
    import { createCounterStore } from "./create-counter-store.ts";
    
    export const [NotificationCountStoreProvider, useNotificationCountStore] = createCounterStore(
      5,
      "notification-count",
    );
    

    Keys must be nonempty, stable across server and browser bundles, and unique per logical store. These two stores are independent; reusing a key shares state. A keyless createStore call that the build did not rewrite throws in the browser, in development and production alike. Only test mode permits keyless calls. Keep utility exports in the helper module: store modules still allow only the tuple and type exports. Render each provider around its consumers; discovery makes a provider hydratable but does not mount it.

    Provider constraints

    #

    Provider props use island prop serialization: pass primitives, plain objects, arrays, and supported rich values such as Date, Map, and Set. Do not pass functions, symbols, arbitrary class instances, request contexts, or services. Provider props are visible in the page's HTML, so never include credentials. The setup return value stays in memory and is not serialized, so it may contain signals, functions, and class instances.

    Mount only one provider for a store on a page. A second active provider with the same identity logs a console.error and leaves the first provider's state active. To replace a provider, unmount the current one first: a committed provider releases ownership on unmount, even before passive effects run, and the replacement initializes state from its own setup. Consumers in other island trees keep the last state until a replacement publishes new state.

    Setup runs in a Preact render context, so hooks such as useSignal and useComputed from brix/hooks can initialize the model. Because a render can be abandoned, keep setup free of external side effects and install subscriptions and cleanup in effects.

    Publication timing

    #
    • Descendants rendered in the provider's own Preact tree read its candidate state synchronously on their first render and in layout effects.
    • Independent browser roots, which includes every other island, read only committed state and see null before the first commit.
    • The provider publishes after its setup-authored layout effects succeed. A render that fails before publication cannot claim shared ownership or publish its candidate.
    • Errors later in the root's commit or passive effects do not undo a published value. Publication is not a transaction: mutations to already-shared objects or signals are not rolled back.

    Recoverable errors need an error boundary in the same browser root, enclosing the provider and its setup. A boundary in another island or server markup cannot catch them. If an exception escapes a Preact root, clearing that root is not guaranteed to run cleanup or release its committed owner. Brix does not install a default root recovery boundary; reload the page to recover a corrupted root rather than assuming that remounting releases ownership.

    Request isolation and shared signals

    #

    In the browser, store state lives in a shared signal registry keyed by store identity. During SSR, each render uses its own registry instead of a process-global value, so concurrent and later requests cannot observe one another's provider state. Server state reaches the browser only through the provider's serialized props; mutable setup return values do not cross that boundary.

    Stores therefore suit page-scoped UI coordination, not server persistence, global caches, or user sessions. For server data freshness and cache ownership, see caching.

    For state that is not request-specific, module-level signals are an alternative. The Preact application build rewrites top-level variable declarations initialized directly by signal(...) from brix/signals (parentheses, as, and satisfies wrappers included), including named aliases and namespace calls such as signals.signal(0), into shared signals keyed by source path (including its extension, so state.ts and state.tsx never share a signal) and variable name:

    src/features/cart/cart-count.ts
    import { signal } from "brix/signals";
    
    export const cartCount = signal(0);
    

    Every island that imports cartCount observes the same signal. The rewrite does not apply to destructuring, function-local calls, factory wrappers, other signal APIs such as computed, or managed React builds. For those cases, call sharedSignal(key, initialValue) from brix/islands with a stable, unique key: in the browser the first call for a key creates the signal and later calls return it, ignoring their initial value. Store keys live in a separate namespace, so a store never shares state with a sharedSignal key.

    On the server, a module-level signal is one value for the whole process, shared by every request. Never put user-specific SSR state in module-level signals; use a store provider instead.

    Test a store

    #

    Use a browser component test to exercise the application's actual store and its update behavior. Name the file booking.client.test.tsx so the browser project discovers it:

    src/features/booking/booking.client.test.tsx
    import { expect, it } from "brix/test";
    import { render } from "brix/test/browser";
    import { BookingStoreProvider, useBookingStore } from "./booking.store.ts";
    
    it("confirms the current booking", async () => {
      function Consumer() {
        const store = useBookingStore();
        if (!store) return <p>No booking</p>;
        return (
          <>
            <button type="button" onClick={store.confirm}>
              Confirm
            </button>
            <p>{store.booking.value.status}</p>
          </>
        );
      }
    
      const screen = await render(
        <BookingStoreProvider initialBooking={{ guestName: "Ada", status: "draft" }}>
          <Consumer />
        </BookingStoreProvider>,
      );
    
      await expect.element(screen.getByText("draft")).toBeVisible();
      await screen.getByRole("button", { name: "Confirm", exact: true }).click();
      await expect.element(screen.getByText("confirmed", { exact: true })).toBeVisible();
    });
    

    Test mode permits the keyless direct calls that the build would otherwise rewrite. Also test the null fallback and provider initialization props. Route tests verify SSR markup; component tests verify browser state changes. Neither proves that separate production island bundles share state after hydration. Use an application E2E test for that boundary: click in one island and assert the changed value in another.

    Managed Storybook catalogs inject identities into direct createStore calls in selected members' *.store.ts files, including static production builds. Two selected apps may use the same relative store path and provider name without sharing state, and application production identities are unchanged. Explicit keys and custom-factory keys remain your responsibility: choose keys unique across all selected members. Render each provider around its story consumers, and verify the static catalog as well as story tests.

    brix check
    brix test --project browser
    brix build
    

    See testing for component and route harness choices.