'React crashing when frequently receiving data from socket.io

I have a react app receiving data every 5 seconds. The server handles it fine, but if you leave the page and come back or wait ~10 seconds, the page will turn white and become unresponsive.

The data contains information for the app to update and display.

I've tried using an async function to process the data, but that doesn't help

socketio client code:

socket.on('UpdateGames', data => {
    const {j, s, e} = JSON.parse(data)
    setJoin(j.map(item => new Game(item)))

    setSpec(s.map(item => new Game(item)))

    setEnd(e.map(item => new Game(item)))
})

Edit: tried sending data every 10 seconds, but the same thing happens



Solution 1:[1]

To add OP @COOKIE's answer, I found that

socket.removeAllListeners([eventName])

solved my issue of a weird recursive loop in my web app.

I believe this is because useEffect starts accruing socket listeners and this exponentially multiplies over time and crashes the web app.

See below for how I solved my issue:

useEffect(() => {
      socket.on(eventName, (res) => {
        func(res);
      });
      return () => socket.removeAllListeners(eventName);
    }
  }, [func, eventName]);

See here for Socket IO docs on this function.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 timbari