Home > Blockchain >  React useEffect unmount cleanup issue
React useEffect unmount cleanup issue

Time:10-03

So I have a component running an useEffect function with some socket.io clean up.

When the component initializes it initializes but runs the socket.disconnect() straight away. Ideally, it should only disconnect when I'm off that page but right now just opening the page with the component initializes socket and also closes connection straight away hence stopping from the web app receiving further broadcasts.. am new to React and trying get a grasp as to why component thinks it dismounted but its clearly visible on the DOM?

adding socket.connect() inside the useEffect didn't solve it either :( it just stays disconnected.

useEffect(()=> {
socket.on("abc", (xy)=> "do something")

return socket.disconnect()}, [])

CodePudding user response:

Your effect is supposed to be returning a function. Try like this,

useEffect(() => {
    socket.on("abc", (xy)=> "do something");
    return (() => {
       socket.disconnect()
    })
}, [])
  • Related