Search code examples
reactjswebsocketreact-hooksuse-effect

websocket connecting multiple times in React


I built a chat app using Websocket in react, however, everytime I refresh the page F5 a new connection is established. It works exactly as expected but it's consuming a lot more than it should be. Is there a way to drop the existing connection whenever a user refreshes the page? ( avoid multiple useless connections) here is where I establish the connection:

  useEffect(() => {
    if (!userInfo) {
      history.push("/login");
    } else {
      if (receiver_id && typeof receiver_id == "number") {
        const url =
          "ws://localhost:8000" +
          "/ws/chat/" +
          receiver_id +
          "/?token=" +
          userInfo.token;
        ws.current = new WebSocket(url);
        if (!connected) {
          ws.current.onopen = function (event) {
            console.log("Connected");
          };
          setConnected(true);
        }

        ws.current.onmessage = function (event) {
          console.log(event);
          console.log("Recieved");
          const dataFromServer = JSON.parse(event.data);
        
        };

        ws.current.onclose = function (event) {
          console.log("Disconnected");
        };

        ws.current.onerror = function (event) {
          console.log("Something is not working, retry.");
        };
      }
    }
  }, [receiver_id, history, userInfo]);

Solution

  • You should terminate the connection in the cleanup function.

    Something like this:

    return () => {
          ws.current.disconnect();
        };