create-react-app: Duplicate Websocket connection only in dev mode

Describe the bug

WebSockets created conditionally and set on a useRef connect twice. This only happens when the app is started in development mode with yarn start but not when the app is served in production from the files generated by yarn build.

Did you try recovering your dependencies?

Yes

Which terms did you search for in User Guide?

useRef, websocket

Environment

Environment Info:

  current version of create-react-app: 4.0.1
  running from /home/chetan/.npm/_npx/1695019/lib/node_modules/create-react-app

  System:
    OS: Linux 5.8 Ubuntu 20.04.1 LTS (Focal Fossa)
    CPU: (12) x64 Intel(R) Core(TM) i7-10710U CPU @ 1.10GHz
  Binaries:
    Node: 12.20.1 - ~/.nvm/versions/node/v12.20.1/bin/node
    Yarn: 1.22.10 - ~/.npm-packages/bin/yarn
    npm: 6.14.11 - ~/.nvm/versions/node/v12.20.1/bin/npm
  Browsers:
    Chrome: Not Found
    Firefox: 84.0.2
  npmPackages:
    react: Not Found
    react-dom: Not Found
    react-scripts: Not Found
  npmGlobalPackages:
    create-react-app: Not Found

Tested on Chromium 87.0.4280.141 and Firefox 84.0.2 on Ubuntu 20.04.

Steps to reproduce

yarn
yarn start

Expected behavior

One websocket connection is made to echo.websocket.org.

Actual behavior

Two websocket connections are made to echo.websocket.org, which are visible in the “Network” tab in browser dev tools.

Screenshot from 2021-01-14 16-27-45

Reproducible demo

https://github.com/chetbox/react-dev-websocket-bug

About this issue

  • Original URL
  • State: open
  • Created 6 years ago
  • Reactions: 2
  • Comments: 22 (1 by maintainers)

Commits related to this issue

Most upvoted comments

This is bad because you can’t abort a websocket which is in readyState==CONNECTING. The component gets unmounted before the connection is fully established.

The unmount lambda then calls websocket.close() making the first connection always break. This triggers the healthcheck and retry policies in my app which makes the app behave differently.

Frankly I am very perplexed on how the useEffect+StrictMode do not take in account this scenario.

I don’t know if this would help anyone but I tried to solve it by adding an event listener to close the websocket when cleaning up useEffect after the websocket open event.

useEffect(() => {
  const ws = new WebSocket(url)
  return () => {
    if (ws.readyState === 1) {
      ws.close()
    } else {
      ws.addEventListener('open', () => {
        ws.close()
      })
    }
  }
}, [])

That is because React.StrictMode renders the component twice (as it is intentional), that causes 2 connections get created.

Create a ws connection inside useEffect and close on the effect cleanup would help or remove StrictMode from index file.

The right way of ensuring double WebSocket connections are not created is to track it as a global variable attached to the window object. Since you must have only 1 connection to your backend anyways (for that tab that is), there is no need to create a new connection in useEffect and attach it to your ref every time component is remounted. Instead, you can check if an existing connection is already bound to a global variable and if it is, then reuse that connection. Also should be checking readyState to see if it was CLOSED or CLOSING when previous component was unmounted. If it was, then it should recreate the connection and rebind the global variable. Here is an example:

  const client = useRef<WebSocket | null>(null)

  useEffect(() => {
    if (!(window.__webSocketClient instanceof WebSocket)) {
      window.__webSocketClient = new WebSocket("ws://your/url/to/socket")
    } else if (
      window.__webSocketClient.readyState === WebSocket.CLOSED ||
      window.__webSocketClient.readyState === WebSocket.CLOSING
    ) {
      window.__webSocketClient = new WebSocket("ws://your/url/to/socket")
    }

    client.current = window.__webSocketClient

    const message = (event: MessageEvent<any>) => {
      console.log("MESSAGE FROM SERVER:", event.data)
    }

    client.current.onopen = () => {
      console.log("ON OPEN CALLED ONLY ONCE")
      client.current?.addEventListener("message", message)

      setTimeout(() => {
        if (client.current?.readyState === WebSocket.OPEN) {
          console.log("SENDING A MESSAGE", client.current.readyState)
          client.current?.send(`Hello from client!`)
        }
      }, 5000)
    }

    return () => {
      console.log("CLEAN UP LISTENER!")
      client.current?.removeEventListener("message", message)
      if (client.current?.readyState === WebSocket.OPEN) {
        console.log("closing socket!")
        client.current?.close()
      }
    }
  }, [])

Types for global variable:

declare global {
  interface Window {
    __webSocketClient: WebSocket
  }
}

Just spent hours debugging my websocket code. It worked fine in Chrome, but wasn’t working in Firefox. Finally figured out that it was creating a connection, closing that and creating a second one. Lots more googling landed me here. Since I’m not seeing another way around this, I am disabling Strict Mode for now. At least I’ll know in the future I can choose one or the other, not both at the same time.

While I appreciate the effort to provide a solution and fully understand the reasons behind the dev mode, the absence of a clean solution is ridicolous. The lifecycle should be provided by the infrastructure. All the other solutions cannot be even called workarounds, but just hacks wasting resources.

This works for me. Only one websocket connection open with a reconnect timer

I put the websocket into a provider here, but that’s not required. You can just use the websocket that you set in state instead

export const WebSocketContext = createContext<{
  websocket: WebSocket | null;
}>({
  websocket: null,
});

export function useWebSocket() {
  const ws = useContext(WebSocketContext);
  return ws;
}

export function WebSocketProvider({ children }: { children: ReactNode }) {
  const [websocket, setWebsocket] = useState<WebSocket | null>(null);
  const reconnectTimer = useRef<Timer | null>(null);

  useEffect(() => {
    const connect = () => {
      const ws = new WebSocket(
        process.env.NEXT_PUBLIC_WEBSOCKET_SERVER_URL as string
      );

      ws.onopen = () => {
        console.log("WebSocket connected");
        if (reconnectTimer.current) {
          clearTimeout(reconnectTimer.current);
        }
      };

      ws.onmessage = (event) => {
        console.log("Message received:", event.data);
      };

      ws.onclose = () => {
        console.log("WebSocket disconnected");
        reconnectTimer.current = setTimeout(connect, 1000);
      };

      setWebsocket(ws);
      return ws;
    };

    const ws = connect();

    return () => {
      ws?.close();
    };
  }, []);

  return (
    <WebSocketContext.Provider
      value={{
        websocket,
      }}
    >
      {children}
    </WebSocketContext.Provider>
  );
}

Just encountered this issue. Tried several ways of tracking the re-render in hopes of creating a connection only on the second render, including trying to cache the connection in a different function but so far no luck. Also, I agree with @raffaeler, socket.close() gets called way before the connection is even established.

It sounds like you should just turn off strict mode. Then your effects will run only once during development. How is that not clean? Nothing is ridiculous when you can opt out.

The strict mode was correctly provided by default to avoid multiple weird bugs. Disabling it is not the right way.

The point of effects running twice are to catch what, in this case, would be a memory leak. You have a component that opens a ws connection on mount, but if you never call close on unmount, you have a leaked connection. Running effects twice in development help highlight when you are leaking resources.

That is not the point. Even when the calls are correctly paired, there are many cases where duplicate begin/end, open/close may cause side-effects such as the case of the websockets (on the backend). The infrastructure should address thoses cases as well.

@shripadk I appreciate the effort, but frankly this lifecycle should be provided in the box with a dedicated hook (or a boolean flag inside useEffect. Please note that Websocket is just a good example, but certainly not the only one requiring a lifecycle tied to the opened window. Thank you anyway.