When i try to console log the message coming from the socket, the connection gets is established and everything is working properly.
import { useState, useEffect } from 'react'
import io from 'socket.io-client'
const App = () => {
const socketio = io('http://localhost:5000')
const [time, setTime] = useState("")
useEffect(() => {
socketio.on('message', msg => {
console.log(msg.time)
})
}, [])
return (
<div className="app">
{time}
</div>
)
}
When i try to do setTime(msg.time)
instead of console.log(msg.time)
hundreds of requests are being sent and my browser crashes.
import { useState, useEffect } from 'react'
import io from 'socket.io-client'
const App = () => {
const socketio = io('http://localhost:5000')
const [time, setTime] = useState("")
useEffect(() => {
socketio.on('message', msg => {
setTime(msg.time)
})
}, [])
return (
<div className="app">
{time}
</div>
)
}
Why is this happening and how can i fix it?
CodePudding user response:
io
has side effects. You create a connection everytime you call it. Because you call it in the render phase, everytime the state of the component is updated, a new connection will be established.
The easiest way to prevent that would be to memoize it.
const socketio = React.useMemo(() => io('http://localhost:5000'), [])
or move it to be part of the state of the component, and connect in a useEffect
.