'Hot reload is duplicating websockets

I am creating a react app and using npm to hot reload the page on save. I am also connecting to a server through socket.io and it works great except that when I save the file and it reloads, it duplicates the socket and creates multiple active socket connections from a single page. Can I close the socket on reload somehow so that I keep only one socket active every time it reloads?



Solution 1:[1]

Try using useRef when creating the socketIOClient. useRef is used to persist values between re-renders E.g. -

const socket = useRef(socketIOClient(ENDPOINT))

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 Abrar Malek