2

When I tried to implement React Router, it seems that I am getting duplicate elements because the socket.on() event is now executing twice.

the router

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <RouterProvider router={router} />
  </React.StrictMode>
);

the route:

const router = createBrowserRouter([
  {
    path: "/",
    element: <TablesView />,
  }
]);

and the code for TablesView

function TablesView() {
  const [games, setGames] = useState([]);
  ...

  useEffect(() => {
    socket.on("room_made", function (msg) {
      // TODO Fix duplicate socket
      var gameID = msg["gameID"];
      var chairs = msg["chairs"];
      setGames((oldGames) => [...oldGames, { gameID, chairs }]);
    });

    socket.on("disconnect", () => {
      setIsConnected(false);
    });

    return () => {
      socket.off("connect");
      socket.off("disconnect");
      socket.off("pong");
    };
  }, []);

return (
...
);
}

I checked the server side code, and nothing is getting emitted twice. So for some reason, it's just hitting the room_made event twice.

But if I remove React.Strictmode, it works fine. Why is this?

Any wisdom would be appreciated!

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
Sam Gates
  • 71
  • 3

1 Answers1

0

This behavior is typical of Strictmode in the development environment. It invokes certain functions twice to help detect unwanted side effects. See more info in the documentation.

This behavior will not occur in production. If you want to stop it from happening in the development environment as well, you can remove the Strictmode tag.