admin管理员组

文章数量:1355648

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!

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!

Share Improve this question asked Mar 28 at 5:45 Sandro TushurashviliSandro Tushurashvili 436 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

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;

本文标签: reactjsHow to properly handle WebSocket connections in a React app with useEffectStack Overflow