Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | // src/hooks/useEventBus.ts
/**
* React hook for subscribing to event bus events
* Automatically handles cleanup on unmount
*
* Based on ADR-036: Event Bus and Pub/Sub Pattern
*/
import { useEffect, useCallback, useRef } from 'react';
import { eventBus } from '../services/eventBus';
/**
* Hook to subscribe to event bus events
* @param event The event name to listen for
* @param callback The callback function to execute when the event is dispatched
*/
export function useEventBus<T = unknown>(event: string, callback: (data?: T) => void): void {
// Use a ref to store the latest callback to avoid unnecessary re-subscriptions
const callbackRef = useRef(callback);
// Update the ref when callback changes
useEffect(() => {
callbackRef.current = callback;
}, [callback]);
// Stable callback that calls the latest version
const stableCallback = useCallback((data?: unknown) => {
callbackRef.current(data as T);
}, []);
useEffect(() => {
// Subscribe to the event
eventBus.on(event, stableCallback);
// Cleanup: unsubscribe on unmount
return () => {
eventBus.off(event, stableCallback);
};
}, [event, stableCallback]);
}
|