React released the new context API and made it official in v16.4.0. The context API is designed to share data that can be considered “global” for a tree of React components. As you can see, it is the perfect candidate for us.

Since some components that need to use the single Socket.IO instance are nested deeply in the React component tree, we are going to create a context instance and store it in a separate file, so that when a component needs it, it can just import it.

Then, in your root component, you can just create a Socket.IO instance and use a Provider to pass the Socket.IO instance to the component tree. After doing this, no matter how deep a component is, it can get the Socket.IO instance.

Say if you have a component which needs to use this Socket.IO instance, you can get the single Socket.IO instance in this way:

By the way, if anyone is interested in the chat room app I am building, you can find it here: https://react.chatboard.com.au. You can also find its source code on GitHub: https://github.com/spencerfeng/chat-board-react.