Socket.io doesn't fire disconnect on browser back button in my React App

Viewed 903

I ran into an issue with react where pressing the browser "back" button on my inner page (thus going back to my outer page) doesn't fire the socket disconnect event. Refreshing, closing the browser, etc fire the disconnect event just fine.

I'm using react-router-dom like so:

const App = () => (
  <Router>
    <Route path="/" exact component={OuterComponent} />
    <Route path="/innercomponent" component={InnerComponent} />
  </Router>
);

I tried to fix this issue by firing socket disconnect on browser back in my InnerComponent:

useEffect(() => {window.onpopstate = e => {
      socket.emit("disconnect");
      socket.off();
      console.log("socket disconnect should fire.");
    };
}

But the disconnect event doesn't fire despite the console.log triggering when I click the back button. I'm assuming this issue is related to the react router.

1 Answers

It's because you are running this effect after each render(thus shutting down the socket, if i understand correctly what's going on), You need to run it only when the component unmounts:

useEffect(()=>{    
    return ()=>{
      socket.close();
    }
  },[])

I don't see a "socket.off()" method, maybe you're using an old version of SocketIO? In the latest version at least, socket.close() is used to shutdown the connection manually. Anyway, i tested it and it seems that this is how your useEffect should be set up.

Related