reactjsreact-hookssocket.iosocket.io-client

socket.io fires event twice in react useEffect hook even though i have unsubscribed in the cleanup function


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


Solution

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