I'm using socketio and react. Im trying to set state for all users when one use changes it but it causes too much rerendering on site.
server.js
const app = require('express')
const http = require('http').createServer(app)
const io = require("socket.io")(http, {
cors: {
origin: "http://localhost:3000",
},
});
let subject = ''
io.on('connection', (socket) => {
socket.on('setSubject', (sbj) => {
subject = sbj
io.sockets.emit('getSubject',subject)
})
socket.on('changeHiddenPassword',hiddenPassword => {
socket.broadcast.emit('newHiddenPassword',hiddenPassword)
})
})
http.listen(4001,function(){
console.log('listening on port 4001')
})
front end
const [hiddenPassword,changeHiddenPassword] = useState([''])
useEffect(() => {
socket.emit('changeHiddenPassword',hiddenPassword)
}, [hiddenPassword]);
socket.on('newHiddenPassword',newHiddenPassword => {
changeHiddenPassword(newHiddenPassword)
})
I dont think rest of the code will help you somehow but if it would i can provide it to you. What i'm trying to do is when someone clicks on specific element on my site i want my hiddenPasword state to change for all connected users. I know that what i'm doing is wrong,beacouse when the state changes for one user useEffect is passing and setting state to everyone else and their useEffect are passing and setting state to everyone else and so on... I want to know how to do it properly and i cant figure out how.
so when you change
hiddenPasswordyou are emittingchangeHiddenPasswordevent, this sends backnewHiddenPasswordevent which changes thehiddenPasswordand this continues infinitely.Try modifying
newHiddenPasswordhandler like this, so it's not changing the state (and triggering useEffect) when the received password is already up to date