reactjswebsocket

How to properly handle WebSocket connections in a React app with useEffect?


I'm working on a React app where I need to establish a WebSocket connection to receive real-time updates. However, I'm facing issues with connections not closing properly when the component unmounts.

Here’s my current approach:

import { useEffect, useState } from "react";

const useWebSocket = (url: string) => {
const [messages, setMessages] = useState<string[]>([]);

useEffect(() => {
 const socket = new WebSocket(url);

socket.onmessage = (event) => {
  setMessages((prev) => [...prev, event.data]);
};

return () => {
  socket.close();
 };
}, [url]);

return messages;
};

export default useWebSocket;

The problem:

Sometimes, the WebSocket connection remains open even after navigating away.

In some cases, I receive duplicate messages when re-opening the same page.

How can I ensure that the WebSocket connection is managed properly to avoid memory leaks and duplicate messages?

Any guidance or best practices would be greatly appreciated!


Solution

  • You can close the existing connection before creating a new connection -

    import { useEffect, useState, useRef } from "react";
    
    const useWebSocket = (url: string) => {
    const [messages, setMessages] = useState<string[]>([]);
    const webSocketRef = useRef<any>(null);
    
    useEffect(() => {
     if (webSocketRef.current) {
          webSocketRef.current.close();
        }
     const socket = new WebSocket(url);
    webSocketRef.current = socket;
    
    socket.onmessage = (event) => {
      setMessages((prev) => [...prev, event.data]);
    };
    
    return () => {
      if (webSocketRef.current) {
            webSocketRef.current.close();
          }
     };
    }, [url]);
    
    return messages;
    };
    
    export default useWebSocket;