Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

244
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!