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.

Reproducible demo
About this issue
- Original URL
- State: open
- Created 6 years ago
- Reactions: 2
- Comments: 22 (1 by maintainers)
Commits related to this issue
- turn off strict mode for now, see: https://github.com/facebook/create-react-app/issues/10387 — committed to MariaTheCoder/chat-app by MariaTheCoder 4 years ago
- chore: react strict mode 임시 제거 - strict mode에선 dev server에서 useEffect가 두 번 실행되는데, 현재 코드에서 useEffect 내에 내부적으로 웹소켓이 호출되는 azure 메서드를 두어 웹소켓 호출 과정에서 에러가 발생하여 음성합성이 제대로 일어나지 않아 소리가 들리지 않는 이슈가 있음. - 해당 로직을... — committed to krafton-jungle-AI-InterviewMate/AI-InterviewMate-FE by ahnanne 4 years ago
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+StrictModedo 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.
That is because
React.StrictModerenders the component twice (as it is intentional), that causes 2 connections get created.Create a ws connection inside
useEffectand close on the effect cleanup would help or removeStrictModefromindexfile.The right way of ensuring double WebSocket connections are not created is to track it as a global variable attached to the
windowobject. 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 inuseEffectand 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 checkingreadyStateto see if it wasCLOSEDorCLOSINGwhen previous component was unmounted. If it was, then it should recreate the connection and rebind the global variable. Here is an example:Types for global variable:
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
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.The strict mode was correctly provided by default to avoid multiple weird bugs. Disabling it is not the right way.
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.