'WebSocket gets disconnected after upgrade to react18

I've noticed something interesting after I've upgraded my react project from version 17.0.2 to version 18.0.0.

On the homepage of my application I'm opening a connection for a WebSocket using SignalR. Everything is running fine with React 17.0.2, but after the upgrade to React 18.0.0, for some reason the WebSocket keeps getting disconnected. After that, I switched back to React 17.0.2 and the issues was fixed.

I'm not really sure why and I couldn't find any questions related to this topic.

The only thing that I did was to update my package.json to use version 18 of react and react-dom and after that in index.js I've made the necessary changes.

If anyone has a similar issues after upgrading to React 18, some informations would be helpful.

Thanks and in the meantime I'll do some more research, maybe I can find out what is the problem.

UPDATE The problem seems to be related to <React.StrictMode> that wraps my entire application's code.

For some reason, when using strict mode, react triggers the useEffect cleanup function that is disconnecting the WebSocket from the HomePage once you leave that page. I've removed the strict mode and now it works fine (this is only available for react 18, if I keep using react 17 with strict mode, I don't have this "issue")

More info here about how React.StrictMode works: https://github.com/reactwg/react-18/discussions/19



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source