0

socket.io in react useEffect renders twice even though i unsubscribed in the cleanup function the code is something like this

 useEffect(() => {
    const callback = (date) => {
      //do something with data
      console.log("new chat received");
    };
    socket.on("new-chat-message", callback);
    return () => {
      socket.off("new-chat-message", callback);
    };
  }, []);

the only way this useEffect hook render once is when i remove the strict mode from the App.tsx similar problems suggests i should remove the event listener on cleanup but that doesn't work for me

Aman
  • 11
  • 4
  • It's not rendering twice, it is mounted twice by the `StrictMode` component as a development check that state is reusable and effects are cleaned up properly. – Drew Reese Jan 14 '23 at 03:03

1 Answers1

1

"the only way this useEffect hook render once is when i remove the strict mode from the App.tsx"

If this is the case, then there's no issue at all.

Strict Mode helps for debugging purposes. Production builds will ignore React.StrictMode - it just gets taken out. Strict mode leads to your components rendering twice if it's not a prod build, which is why you're seeing the log twice.

So, you're all good.

  • then what good is socket.off("new-chat-message", callback); for besides memory cleaning – Aman Jan 14 '23 at 06:16
  • Memory cleaning. Lol. E.g. if you add a window event listener in a component, you have to clean it up on the useEffect's return, otherwise that event listener will linger after the component is unmounted. Which is bad. –  Jan 14 '23 at 15:20