1

i have a function that gets called by a socket.io's event:

const [room, setRoom] = useState({})
const [messages, setMessages] = useState([])

function reciveMessage(message) {
 if (room.id == message.roomid) {
  setMessages(messages => [...messages, message])
 }
}

the room state value is stale

if i try to work around it by

setRoom(room => {
 if (room.id == event.data.source.conId) {
  setMessages(messages => [...messages, message])
 }
 return room
})

the room value is the lastest but setMessage runs twice is there a better way?

1 Answer 1

1

A socket message is a side-effect, so handle it in useEFfect.

useEffect(() => {
    // do whatever it is to set up the message subscription/connection
    // and call `setMessages([...messages, message])` when
    // one is received in the handler/callback
    return () => {
        // clean-up, e.g., closing connection, etc. 
    }

}, 
// will only re-run the effect if the id changes
[room.id])

setMessages will only be called when a message is received. If the room.id changes, then the useEffect code will be run again, subbing to the new room.

Sign up to request clarification or add additional context in comments.

3 Comments

is re-running a new subscription everytime a room changes a bad practice? (not very often) also thankyou i totally forgot you can do that and i was trying to keep the connection on as long as possible.
@Tera I didn't know if that would be something you'd need to do or not. If the room changing doesn't require any connection changes, you don't have to do that. You could just run the effect once to establish your connection in that case.
React provides an example of using useState that involves changing the state within the callback. So one would think that using useState in this way is not generally discouraged.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.