Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

190
Views
React.js and Websocket.io ends up in infinite Loop

i want to write a game Lobby for a card game. Using React.js, Node.js and Websocket.io for achieving this. As so far all went fine. Players are connected in the same Lobby. But i want to print in the Lobby sth Like (Player 1: Steven, Player 2: Frank, ...). I ended up in an infinite loop, i am trying to solve since hours. So maybe someone can help me. It keeps re-rendering by useState i guess, but i don't know how to prevent it from.

Relevant Frontend Code:

const Lobby = (props) => {
  const socket = props.socket;
  const player = {
    room: props.room,
    name: props.name,
  };

  const [playerList, setPlayerList] = useState([]);

  socket.emit("joined_lobby", player);
  console.log(`${playerList}`);

  useEffect(() => {
    socket.on("add_user", (data) => {
      setPlayerList([...playerList, data.name]);
    });
  }, []);

Relevant Server Code:

io.on("connection", (socket) => {   console.log(`Player with ID:\[${socket.id}\] Connected`);

  socket.on("join_room", (data) => {
    socket.join(data);
    console.log(`Player with ID:\[${socket.id}\] Joined the room ${data}`);   });

  socket.on("joined_lobby", (data) => {
    socket.to(data.room).emit("add_user", data);   });

  socket.on("disconnect", () => {
    console.log(`Player with ID:\[${socket.id}\] Disonnected`);   }); });
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

i would like to say i am currently passing through quite the same challenge, looking out for the solution

about 4 years ago · Juan Pablo Isaza Report

0

Sounds like you only want to run socket.emit("joined_lobby", player); once per 'player'.

If so, move it into a useEffect, and make it so it runs only if the room or player name changes.

useEffect(() => {
 const player = {
    room: props.room,
    name: props.name,
  };

   socket.emit("joined_lobby", player);
   
  return () => {
    // I invented this - you need a way of dealing with leaving
    // e.g. if the room changes
    socket.emit("left_lobby", player);
  } 
  
},[props.room, props.name]);

EDIT: you may need to put props.socket in the deps too - I don't know how the lifecycle of that one works

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!