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

1

There are 1 best solutions below

2
On BEST ANSWER

"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.