I have a React component that establishes a connection with a socket io server. When the component unmounts, should it automatically disconnect via a useEffect?
If yes, then what is the syntax to disconnect from a React component to Socket io server?
No, you don't need to do it when you need Socket in other components. But I think you mean unbinding events, then Yes of course you need to unbind it.
BTW, if you want to disconnect, replace socket.off with socket.disconnect in the code below.
I use such this syntax:
function Helper() {
const socket = useSocket; // my custom hook that returns a socket instance.
useEffect(()=> {
socket.emit("FOO_BAR", "BLA_BLA");
socket.on("CALL_ME", handleCall); // handleCall is a cb somewhere in my code
return () => {
socket.off("CALL_ME", handleCall);
}
}, [socket]);
}