Tom
Tom

Reputation: 123

How to correctly inititate socket.io connection on the client side with ReactJS?

Hi I'm making a card game and i've been able to connect my client side with my socket.io server but the problem is my client sends a lot of requests when connecting to the server.
I'm using ReactJS on the client side and ExpressJS + socket.io on the server side.
On the client side:

const Room = () => {
  const dispatch = useAppDispatch();
  const params = useParams() as any;
  const user = useAppSelector(selectUser);
  const room = useAppSelector(selectRoom);
  const [socket] = useState<Socket<DefaultEventsMap, DefaultEventsMap>>(io('http://localhost:3000'));

  useEffect(() => {
    if (params.id) {
      dispatch(getRoom(params.id));
    }
    return () => { socket.disconnect(); };
  }, []);

  useEffect(() => {
    if (user.name && room.id) {
      socket.emit(JOIN_ROOM, {
        user: {
          name: user.name,
          money: user.money,
        },
        roomId: room.id,
        random_seat: room.random_seat,
        max_number_of_player: room.max_number_of_player,
      });
    }
    return () => {
      socket.emit(LEAVE_ROOM, {
        username: user.name,
        roomId: room.id,
      });
    };
  }, [user.name, room.id]);

And on the server side:

const onConnection = (socket) => {
  roomHandler(io, socket, store);
  chatHandler(io, socket);
  socket.on('disconnect', function() {
    console.log("User has disconnected: " + socket.id)
  });
}

When i reload the page i see this log:

User has disconnected: mxh8AqLWSvpB9IqtAAAs
User has disconnected: KefLTWmzHwt4yxi7AAAt
User has disconnected: cNyOJtqX4gLRlkSFAAAv
User has disconnected: hWjpCSx6-fypEcp1AAAu
User has disconnected: D407Grg1YgpLz6V-AAA2
User has disconnected: KN5gWEZSkI4tvqZ2AAA1
User has disconnected: 6QY_pzmugv7hQuZiAAA0
User has disconnected: nunKDWVRiishLsCbAAA3

So when i reload, only one user has disconnected but along with it are multiple socket connections.
I'm initiating the connection by using useState and store the client socket instance as a state which is passed down as props so children component can use it and emits/listens to event.
If i open my network tab in the browser i can also see lots of request made to my server side.
What am i doing wrong here?

Upvotes: 0

Views: 596

Answers (1)

AJcodez
AJcodez

Reputation: 34236

Every time this component renders, it will call io('url') and create a new connection. Instead, create the connection in useEffect once and keep a reference.

const socket = useRef();

useEffect(() => {
  socket.current = io('url');
  return () => {
    socker.current.disconnect()
  };
}, []);

Upvotes: 1

Related Questions