1

What is the correct way to structure a websocket connection within a React app where the socket port is loaded via a RESTful call on page load?

  1. User loads React App
  2. RESTful GET request for socket port (fetch) E.g. http://example.com:1234/port //-> { "port": 9999 }
  3. Construct websocket URI from response
  4. Connect (Native ws or socket.io-connect)
  5. Set up callbacks (onmessage)
  6. Monitor connection status. Attempt to reconnect if disconnected

...all within a functional app.

The main problems are:

  1. the synchronization of the RESTful call for the ws port. Here I am considering a promise [Ref 0]?

  2. The socket reconnecting on each render. Calls in the onmessage use hooks, and so must be in the function body. Here possibly a ws status check before a reconnect? [Ref 1]

How is this properly structured?

I'm also considering a separate class or function dedicated to handling the ws connection.

  1. Javascript - Using Promises on Websocket?
  2. What is best practice to websocket reconnect in react?
kmiklas
  • 13,085
  • 22
  • 67
  • 103
  • For 1: What does the call for the port have to do with promisifying your websocket connection as shown in your ref? You will use a regular fetch to get the port, which you can await and then connect to the websocket. For 2: Make sure you are using the dependency array as a seocnd parameter to useEffect (in case you are using this) to prevent react from re-executing the code when it's not necessary. If there are no dependencies, use an empty array (https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects). Without code it's hard to give more specific answers. – Philip Feldmann Sep 15 '20 at 11:58

0 Answers0