Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

246
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda