Sharing Websocket In React Components

Often times there is a requirement to share a common websocket connection between React components. I have been using the React Context API to do that. Example for

In this case there is a top level component file App.js where the socket is initialized and then made available to other React Components like HomePageComponent.js (which are its children) using Context.

A common pattern while using Context is to write a Provider for the children. In that case, after initializing the websocket in App.js, any other component(s) can be provided access to the websocket via its props by wrapping it in the provider like this:

render() {
  return (
      <MyComponent1 />
      <MyComponent2 />

Here the SocketProvider is:

and is accessible in MyComponent1 and MyComponent2 as this.props.socket. Note that this SocketProvider only provides the websocket one level deep - children of MyComponent1 do not get to use the websocket unless they are wrapped in SocketProvider themsevles. Also note that { ...this.props, { socket: this.socket }} is a shallow merge.