React
React projects use @busly/react, a small package with two hooks and an optional provider. If you manage state with Zustand, there's also @busly/zustand, covered further down this page.
Installation
pnpm add @busly/react @busly/core @busly/eventsnpm install @busly/react @busly/core @busly/eventsbun add @busly/react @busly/core @busly/eventsIf you use Zustand, add @busly/zustand and @busly/js as well (see Using on Zustand projects):
pnpm add @busly/react @busly/core @busly/events @busly/zustand @busly/jsnpm install @busly/react @busly/core @busly/events @busly/zustand @busly/jsbun add @busly/react @busly/core @busly/events @busly/zustand @busly/jsThe adapter requires React 18 or newer. The examples on this page use a counterEvents group, defined at module level:
import { eventGroup, type } from '@busly/events';
export const counterEvents = eventGroup({
source: 'Counter',
events: {
increment: type<void>(),
set: type<number>(),
saved: type<number>(),
},
});Dispatching events in React
To send events from a component, call useBusDispatch with an event group. You get back one function per event:
import { useBusDispatch } from '@busly/react';
import { counterEvents } from './counter.events';
export function Controls() {
const counter = useBusDispatch(counterEvents);
return (
<>
<button onClick={() => counter.increment()}>+1</button>
<button onClick={() => counter.set(0)}>Reset</button>
</>
);
}The returned object stays the same across renders as long as the group and the source don't change, so it's safe to use in dependency arrays and as a prop to memoized components. Its methods are plain closures, which means you can destructure them freely, as in const { increment } = counter.
Two small things are worth watching out for. When you use a method as an onClick handler, wrap it in an arrow function as shown above; passed directly, React would hand it the click event, which would become the payload and fail to clone. And keep your groups at module level. A group written inline is a new object on every render, which gives you a new dispatcher every time.
Source
Events sent from React carry the source 'busly-react' unless you say otherwise. The simplest way to set it for your whole application, or any part of it, is to wrap that part in a BusProvider:
import { BusProvider } from '@busly/react';
createRoot(el).render(
<BusProvider source="checkout-mfe">
<App />
</BusProvider>,
);You can also set it for a single hook, with useBusDispatch(counterEvents, { source: 'cart-widget' }). When both are present, the hook's option wins over the nearest provider, and the provider wins over the default.
Listening to events in React
To react to events, use useBusEvent. It subscribes while the component is mounted and unsubscribes when it unmounts:
import { useState } from 'react';
import { useBusEvent } from '@busly/react';
export function Count() {
const [count, setCount] = useState(0);
useBusEvent(counterEvents.set, ({ payload }) => setCount(payload));
useBusEvent(counterEvents.increment, () => setCount((n) => n + 1));
return <span>{count}</span>;
}Several events
You can also pass an array of creators to handle several events in one place:
useBusEvent([counterEvents.increment, counterEvents.set], (event) => {
log(event.type, event.source, event.ts);
});An empty array throws an error, and listing the same type twice still delivers each event only once.
Behavior
The hook is designed so you don't have to think about memoization. It always calls the latest handler you passed, so the handler sees fresh props and state without useCallback. Passing a new function or a new array on every render doesn't cause it to resubscribe either; it only resubscribes when the set of event types actually changes.
It also behaves well under StrictMode, where the double mount is handled safely. And if one handler throws, the others still run.
One single event handler in pure React contexts
You may notice that @busly/react doesn't offer the on and lazy cohorts found in other adapters. That's intentional.
The point of lazy is to run after on has written state, so that effects can read it. In React, though, setState only queues an update. The new value shows up on the next render, after every handler for the event has already run, so a lazy handler would still see the old state. The order would hold, but it wouldn't accomplish anything.
Fortunately, React already gives you the ordering you need, with a single handler per event. If a side effect only needs the data in the event, do it right in the handler, next to the state update. If it depends on the updated state, put it in a useEffect that watches that state, because effects run after React has applied the update:
function Cart() {
const [items, setItems] = useState<Item[]>([]);
useBusEvent(cartEvents.added, ({ payload }) => {
setItems((list) => [...list, payload]); // state
track('cart_add', payload.id); // effect, from payload
});
useEffect(() => {
localStorage.setItem('cart-size', String(items.length)); // effect, from state
}, [items.length]);
return <CartList items={items} />;
}Things change when your state lives outside React, in a store whose writes are synchronous. Zustand is a good example, and that's where on and lazy become useful again.
Using on Zustand projects
@busly/zustand lets you reduce Busly events straight into a Zustand store.
pnpm add @busly/zustand @busly/js @busly/core zustandnpm install @busly/zustand @busly/js @busly/core zustandbun add @busly/zustand @busly/js @busly/core zustandMiddleware: busly
The busly middleware lets you declare the store and its event wiring together, in a single expression:
import { create } from 'zustand';
import { createDispatcher } from '@busly/js';
import { busly, on } from '@busly/zustand';
import { counterEvents } from './counter.events';
const counter = createDispatcher(counterEvents);
interface CounterState {
count: number;
set: (n: number) => void;
increment: () => void;
}
export const useCounter = create<CounterState>()(
busly(
() => ({
count: 0,
// actions dispatch instead of calling set(): one path updates every context, this one too
set: (n) => counter.set(n),
increment: () => counter.increment(),
}),
on(counterEvents.set, ({ payload }) => ({ count: payload })),
on(counterEvents.increment, (_event, state) => ({ count: state.count + 1 })),
),
);Components then read from the store just as they would from any other Zustand store:
function Count() {
const count = useCounter((s) => s.count);
const increment = useCounter((s) => s.increment);
return <button onClick={increment}>{count}</button>;
}Each reducer receives the event and the current state, and returns a partial state that setState merges in. Reducers run in the order you declare them, so if two of them handle the same event, the second one sees the result of the first.
Notice that the actions in this example dispatch events instead of calling set(). That way, the reducers are the only path that changes state, in this context and in every other one. The trade-off is that local state updates one microtask later.
busly composes with other middleware, such as devtools, persist, or subscribeWithSelector, just like any Zustand middleware. Its wiring lives as long as the store does, and there's no way to remove it.
Existing store: busReducer
When you need wiring you can remove later, or when the store comes from code you don't control, use busReducer. It applies the same cases to an existing store, whether that's a hook from create or a vanilla createStore, and returns a function that removes them:
import { busReducer, on } from '@busly/zustand';
const off = busReducer(
useCounter,
on(counterEvents.set, ({ payload }) => ({ count: payload })),
);
off(); // removes every case it registeredThe on / lazy event handlers in React with Zustand
Here's where the two cohorts pay off. Zustand reducers run in the @busly/js on cohort, and Zustand's setState is synchronous. As a result, any lazy handler from @busly/js reads the store after it's been reduced, no matter when that handler subscribed:
import { createDispatcher, createReceiver } from '@busly/js';
const counter = createDispatcher(counterEvents);
// effects: lazy cohort, module level or in a component effect
createReceiver().lazy(counterEvents.set, async () => {
const count = useCounter.getState().count; // already reduced
await api.save(count);
counter.saved(count);
});If the effect belongs to a component, tie the receiver to a useEffect so it's cleaned up on unmount:
useEffect(() => {
const receiver = createReceiver();
receiver.lazy(counterEvents.set, () => toast(`Count: ${useCounter.getState().count}`));
return () => receiver.dispose();
}, []);To sum up which tool fits which job:
| Need | Use |
|---|---|
| State in a Zustand store | busly / busReducer + on |
| Effects reading reduced store state | @busly/js createReceiver().lazy |
| Dispatch from components | useBusDispatch or @busly/js createDispatcher |
| Component-local state | useBusEvent + useState |
Keep in mind that the order holds within a single copy of @busly/js. If several microfrontends need it to hold across them, they should share that copy, through module federation or import maps.
Server-side rendering
The package is marked 'use client', and it stays out of the way on the server. useBusEvent never registers anything there, since effects don't run on the server. The functions returned by useBusDispatch do nothing when called during server rendering or from server actions, and busly and busReducer don't wire anything either.
As a consequence, state that comes from Busly events won't be part of the server-rendered HTML. If the server needs to render some state, load it the usual way.