I just updated to React 18 and I noticed that the useEffect runs twice which makes my socket io code fail connection. What could be the solution for this?
Here is my useEffect:
useEffect(() => {
dispatch(connect());
return () => dispatch(disconnect());
}, []);
This is supposed to run on mount so just once but with the new changes in React 18, it does not. I get the following error:
WebSocket connection to 'ws://localhost:4444/socket.io/?EIO=4&transport=websocket&sid=tvz2_YPur_k2czFbAAAo' failed: WebSocket is closed before the connection is established.
When I remove the StrictMode, it works fine as usual so the problem comes from the new useEffect change in react 18.
EDIT:
So I played with it more and I noticed that if I remove the return () => dispatch(disconnect())
from the cleanup, it works fine.
Why would that be?
Like this:
useEffect(() => {
dispatch(connect());
}, []);
2
Answers
In your case, you can add an empty dependency array to ensure that the effect only runs once when the component mounts:
try this code to connect websocket:
Make sure websocket package has been installed
npm i websocket --develop
Unfortunately WebSockets are a stateful communication layer, and React tries to be a stateless library. React 18 strict mode always mounts and unmounts multiple times reveal statefulness.
You could try https://www.npmjs.com/package/react-use-websocket, a library that has a global socket manager outside of React that gives you access to sockets.