最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

reactjs - How to properly handle WebSocket connections in a React app with useEffect? - Stack Overflow

programmeradmin1浏览0评论

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;
发布评论

评论列表(0)

  1. 暂无评论