Manage multiple websockets with React

I’m currently working on a React.js based SPA using a JSON RPC 2.0 backend API. This API is based on websockets and requires to open and manage multiple websocket connections simultaneously across multiple React.js components.

First I thought to manage these socket connections using the React Context API with a custom provider component holding the connection state and updating the context and a HOC/Hook.

ReactDOM.render(
    <WebsocketProvider>
        <App />
    </WebsocketProvider>,
    document.getElementById('root')
);

...

export default withWebsocket(App);

This works pretty well for a single connection, but it doesn’t scale for multiple connections. A global store like Redux doesn’t seem to be the right place for holding socket connections!

My second approach was to completely remove the management of the websocket connections from the React lifecycle and to let the react components use a kind of service singleton.

class MyComponent extends React.Component {

    componentDidMount () {
        const socket = SocketService.get(this.socketId);
        socket.addEventListener('message', () => { this.setState({ ... }) });
    }
}

This approach works in principle, but it looks like a lot of hacking to me to simply use a map with unique identifiers.

Most suggestions recommends the React Context API or a Redux middleware for sharing a websocket connection. But how to manage multiple connections across components? Any recommendations or further ideas?

Source: Ask Javascript Questions

LEAVE A COMMENT