Managing Multiple WebSocket Connections in React with Shared Connections for Components Using the Same URL

I’m working on a React application where I need to manage multiple WebSocket connections. Specifically, I want different components to be able to share a connection if they use the same URL. I’m using SignalR for WebSocket communication and have implemented a context and a custom hook for managing these connections.

The goal is to have a single WebSocket connection per URL that can be shared among multiple components, and properly manage the lifecycle of these connections (i.e., establish, share, and disconnect connections as needed).

I have tried a bunch of different things to get the desired behaviour, but sadly im unable to create a satisfactory solution. Currently, I’m experiencing an issue where the WebSocket connection is established correctly but then unmounts and removes itself almost immediately. In general i have had a lot of problems regarding “race condtions”, which have been caused by multiple components simuntaniously trying to establish a connection. Any help would be much appreaciated.

Here is the relevant code. If you feel any code is missing or that my question is unclear, i would love to further explain the problem.

import { HubUrls, SignalRContext } from "@/providers/SignalRProvider";
import { HubConnection } from "@microsoft/signalr";
import { useContext, useEffect, useState } from "react";

const useSignalR = (url: HubUrls): { connection: HubConnection | null, error: Error | null, loading: boolean } => {
    const context = useContext(SignalRContext);
    const [connection, setConnection] = useState<HubConnection | null>(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<Error | null>(null);

    if (!context) {
        throw new Error('useSignalR must be used within a SignalRProvider');
    }

    useEffect(() => {
        let isMounted = true;

        const setupConnection = async () => {
            try {
                const conn = await context.getConnection(url);

                if (isMounted) {
                    setConnection(conn);
                    setLoading(false);
                }
            } catch (err) {
                if (isMounted) {
                    setError(err as Error);
                    setLoading(false);
                }
            }
        };

        setupConnection();

        return () => {
            isMounted = false;
            context.releaseConnection(url);
        };
    }, [context, url]);

    return { connection, error, loading };
};

export default useSignalR;
"use client";
import React, { createContext, useContext, useEffect, useState, ReactNode } from 'react';
import { HubConnection, HubConnectionBuilder, LogLevel } from '@microsoft/signalr';
import useAuthContext from "@/providers/AuthProvider";

export const BASE_URL = 'http://localhost:5040';
export type HubUrls = '/chat' | '/kanban' | '/logbook';

const createConnection = (url: HubUrls, getToken: () => Promise<string>): HubConnection => {
  return new HubConnectionBuilder()
      .withUrl(`${BASE_URL}${url}`, {
        accessTokenFactory: getToken,
      })
      .configureLogging(LogLevel.Information)
      .withAutomaticReconnect()
      .build();
};

const globalHubRegistry: Record<string, { connection: Promise<HubConnection>, subscribers: number }> = {};

const getOrCreateWebSocket = async (url: HubUrls, getToken: () => Promise<string>): Promise<HubConnection> => {
  if (globalHubRegistry[url]) {
    globalHubRegistry[url].subscribers += 1;
    return globalHubRegistry[url].connection;
  } else {
    const connection = createConnection(url, getToken);
    const connectionPromise = connection.start().then(() => {
      globalHubRegistry[url] = { connection: Promise.resolve(connection), subscribers: 1 };
      return connection;
    }).catch(err => {
      delete globalHubRegistry[url];
      throw err;
    });

    globalHubRegistry[url] = { connection: connectionPromise, subscribers: 1 };
    return connectionPromise;
  }
};

const unsubscribeWebSocket = async (url: HubUrls): Promise<void> => {
  if (globalHubRegistry[url]) {
    globalHubRegistry[url].subscribers -= 1;
    if (globalHubRegistry[url].subscribers === 0) {
      console.log("Deleting connection" + url);
      const connection = await globalHubRegistry[url].connection;
      await connection.stop();
      delete globalHubRegistry[url];
    }
  }
};

interface SignalRContextProps {
  getConnection: (url: HubUrls) => Promise<HubConnection>;
  releaseConnection: (url: HubUrls) => void;
}

export const SignalRContext = createContext<SignalRContextProps | undefined>(undefined);

const SignalRProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const { getToken } = useAuthContext();

  const getConnection = (url: HubUrls): Promise<HubConnection> => {
    return getOrCreateWebSocket(url, getToken);
  };

  const releaseConnection = async (url: HubUrls): Promise<void> => {
    await unsubscribeWebSocket(url);
  };

  return (
      <SignalRContext.Provider value={{ getConnection, releaseConnection }}>
        {children}
      </SignalRContext.Provider>
  );
};

export default SignalRProvider;

New contributor

MertzAndeas is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật