I'm trying to build a realtime chat message. In the client's side (React), whenever a new user enters the chat, the socket's event usuarios-conectados gets triggered (this socket event gives me an array of all the users connected at the time).
Then, I tried to set that array of users in a useState, but because of that, the component goes into a loop and keeps re-rendering itself.
That seems to be the problem because whenever i call useSocket, the console.log(users) keeps printing the connected users over and over
import { useEffect, useState } from 'react'
import { io } from "socket.io-client";
export const useSockets = () => {
const [socket, setSocket] = useState(
io('http://localhost:8080', {
'extraHeaders': {
'x-token': localStorage.getItem('x-token')
}
})
)
const [users, setUsers] = useState([])
useEffect(() => {
socket.on('connect', () => {
console.log('Sockets online')
})
socket.on('usuarios-conectados', (newUsers) => {
setUsers(newUsers);
console.log(users);
})
return () => {
socket.on('disconnect', () => {
console.log('Sockets offline')
})
socket.disconnect()
}
}, [])
return [users]
}