Mike B.
Mike B.

Reputation: 133

useState what am I doing wrong?

I'm creating an app that reads the alarm state of several ELK alarm systems. I'm using useState to process the data that I am receiving via socket.io from my server. The data that the server is streaming is an array of arrays.

This is the code that I am using:

const [startData, updateData] = React.useState([]);

  const socket = io("http://localhost:5000");

  socket.on('data', (dta) => {
    updateData(dta.data);
  });

If I console.log(startData) then it becomes evident that my code is causing an infinite loop. I read through examples of users in this forum with similar issues but I wasn't successful in tailoring their solutions to my problem. I was somewhat able to manage the amount of requests with setTimeout but after the app is running for about 2 hours, the page becomes unresponsive (memory leak????).

Do you people have any suggestion on how I could improve my code?

Upvotes: 1

Views: 88

Answers (2)

Hamid Shoja
Hamid Shoja

Reputation: 4768

actually as Jonas said you should call socket once:

import socketIOClient from "socket.io-client"; 

const [startData, updateData] = React.useState([]);
  const endpoint= "http://localhost:5000";
  useEffect(() => {

       //Very simply connect to the socket
       const socket = socketIOClient(endpoint);

       //Listen for data on the "outgoing data" 
       socket.on("outgoing data", (dta)=>updateData(dta.data));
       });
    }, []);

this is a good example : express socket react

Upvotes: 0

Jonas Wilms
Jonas Wilms

Reputation: 138257

listening to a socket should only happen once, also this is a side effect, both are indicators that these should be inside a useEffect hook:

 useEffect(() => {
   const socket = io("http://localhost:5000");

   socket.on('data', (dta) => {
     updateData(dta.data);
   });
 }, []);

Unlike the functions body, which will be run on every rerender, the effect hook will only run on specific state changes, or only once in this case.

Upvotes: 3

Related Questions