I’m new to React and I’m having some issues regarding components structure and sharing a websocket between them.
The app consists of categories and products. The initial data load will be done with an Ajax request and a websocket will be used keep data updated.
My component hierarchy looks like this:
- CategoriesList
- Category
- ProductsList
- Product
- ProductsList
- Category
CategoriesList holds the state of categories and ProductsList holds the state of products within a category.
So I would like to use the same websocket inside CategoriesList and ProductsList but listening to different websocket events: category:updated and product:updated.
How do I share the websocket between components and where is the right place to initialize it?
Since there is one ProductsList for each Category, does this means that the products:updated event will fire multiple times ( one for each category )? I guess this isn’t a good thing in terms of performance.
Advertisement
Answer
I recommend initializing your socket connection in CategoriesList and then passing down the connection as props to the child components. When the connection is passed down, you should be able to use it to listen for specific events as needed in the child components.
Here’s an example application on github that uses react and socket.io. The socket is initialized in a parent component and then passed down. https://github.com/raineroviir/react-redux-socketio-chat/blob/master/src/common/containers/ChatContainer.js
On line 9 the connection is initialized and then on line 23 it’s passed down as props. The connection is later used in child components to receive and emit events. Ex: https://github.com/raineroviir/react-redux-socketio-chat/blob/master/src/common/components/Chat.js