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
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])