React crashing when frequently receiving data from socket.io

Viewed 602

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

2 Answers

Evert was correct that I didn't have any cleanup. Added this to my component

useEffect(() => {
    socket.on('connect', socket => {
        console.log('connected')
    })

    socket.on('UpdateGames', data => {
        const {j, s, e} = JSON.parse(data)

        console.log("RECEIVE")

        setJoin(j.map(item => new Game(item)))

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

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

    return () => socket.off('UpdateGames', listener)
}, [])

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.

Related