(ETabMode.PRIMARY);
-
- useEffect(() => {
- channelRef.current = new BroadcastChannel(channelName);
+ React.useEffect(() => {
+ if (typeof window !== "undefined" && "BroadcastChannel" in window) {
+ channelRef.current = new BroadcastChannel(channelName + "-channel");
+ }
}, [channelName]);
- useEffect(() => {
- if (channelRef.current) {
- channelRef.current.addEventListener("message", (event) => {
- if (mode === ETabMode.PRIMARY) {
- setValue(event.data);
- setMode(ETabMode.SECONDARY);
- }
- });
- channelRef.current.postMessage(initialValue);
+ useChannelEventListener(channelRef.current, "message", handleMessage);
+ useChannelEventListener(
+ channelRef.current,
+ "messageerror",
+ handleMessageError,
+ );
+
+ return React.useCallback(
+ (data: T) => channelRef.current?.postMessage(data),
+ [channelRef.current],
+ );
+}
+
+/**
+ * React hook to manage state across browser windows. Has the similar signature as `React.useState`.
+ *
+ * @param channelName Static name of channel used across the browser windows.
+ * @param initialState Initial state.
+ * @returns Tuple of state and setter for the state.
+ * @example
+ * ```tsx
+ * import {useBroadcastState} from 'react-broadcast-channel';
+ *
+ * function App () {
+ * const [count, setCount] = useBroadcastState('count', 0);
+ * return (
+ *
+ *
+ * {count}
+ *
+ *
+ * );
+ * }
+ * ```
+ * ---
+ * Works in browser that support Broadcast Channel API natively. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API#browser_compatibility).
+ * To support other browsers, install and use [broadcastchannel-polyfill](https://www.npmjs.com/package/broadcastchannel-polyfill).
+ */
+export function useBroadcastState(
+ channelName: string,
+ initialState: T,
+): [T, React.Dispatch>, boolean] {
+ const [isPending, startTransition] = React.useTransition();
+ const [state, setState] = React.useState(initialState);
+ const broadcast = useBroadcastChannel(channelName, (ev) =>
+ setState(ev.data),
+ );
+ const updateState: React.Dispatch> =
+ React.useCallback(
+ (input) => {
+ setState((prev) => {
+ const newState = typeof input === "function" ? input(prev) : input;
+
+ startTransition(() => broadcast(newState));
+
+ return newState;
+ });
+ },
+ [broadcast],
+ );
+
+ return [state, updateState, isPending];
+}
+
+// Helpers
+
+/** Hook to subscribe/unsubscribe from channel events. */
+function useChannelEventListener(
+ channel: BroadcastChannel | null,
+ event: K,
+ handler?: (e: BroadcastChannelEventMap[K]) => void,
+) {
+ const callbackRef = React.useRef(handler);
+
+ if (callbackRef.current !== handler) {
+ callbackRef.current = handler;
+ }
+
+ React.useEffect(() => {
+ const callback = callbackRef.current;
+
+ if (!channel || !callback) {
+ return;
}
- return () => {
- if (channelRef.current?.onmessage) {
- channelRef.current.onmessage = null;
- }
- channelRef.current?.close();
- };
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [channelName, initialValue]);
+ channel.addEventListener(event, callback);
- const send = (data: EBCEvent) => {
- channelRef.current?.postMessage(data);
- };
-
- return { mode, value, send };
-};
+ return () => channel.removeEventListener(event, callback);
+ }, [channel, event]);
+}