Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

UseEffect is not running cleanup on-dismount

I have a MessageInput component which triggers a socket connection to the backend when it mounts, and should disconnect from that socket manually on dismount. I am not sure what happened, but at some point yesterday useEffect simply stopped running cleanup.

When I close the app I see the accumulated disconnections all at once.

User disconnected...
User disconnected...
User disconnected...

Is there something I am missing in useEffect?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here is my code:

useEffect(async () => {
    const accessToken = await SecureStore.getItemAsync("access-token");
    const socket = socketClient(`${process.env.REACT_APP_backend_url}/`, {
      auth: {
        authToken: accessToken,
      },
    });
    socket.emit("message", message);
    return () => socket.disconnect();
  }, []);

>Solution :

async functions return promises, so you’re not actually returning a cleanup function. React ignores the promise that you return to it.

You’ll need to do something like this:

useEffect(() => {
  let socket;
  (async () => {
    const accessToken = await SecureStore.getItemAsync("access-token");
    socket = socketClient(`${process.env.REACT_APP_backend_url}/`, {
      auth: {
        authToken: accessToken,
      },
    });
    socket.emit("message", message);
  })()

  return () => {
    if (socket) {
      socket.disconnect();
    }
  }
}, []);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading