Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

245
Visualizações
reactjs websocket in a browser client: use the socket connection inside an effect hook

I have a reactjs client that connects to a websocket server, however when I try to initialize it outside of an effect hook, the websocket object is undefined, but it initializes when its in an effect hook

like so:

effect(()=>{
  connection = new WebSocket(url)
  //do some stuff
})

the issue is that I want to send things based on an event that happens in the reactjs app

effect(()=>{
  connection.send(messages)
},[messages])

at that point, connection is undefined, despite the connection being made then, I can only assume that since I have to use the Native WS for browsers, I have to initialize the websocket elsewhere, but I don't know where

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Maintain state variable for connection. Create only one time and have close connection in effect. (Empty dependency array to run once)

const [connection, setConnection] = useState(null);

useEffect(() => {
  connection = new WebSocket(url);
  setConnection(connection);
  return () => connection.close()
}, [])

useEffect(() => {
  connection.send(messages)
}, [messages])
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda