Reactjs: how to share a websocket between components

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

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Another way of sharing the same instance is simply create a new file as below: socketConfig.js

import openSocket from 'socket.io-client';

const socket = openSocket("http://localhost:6600");

export default socket;

and the use it in any file you want, just import it.
import socket from "../socketConfig";

This works for me, as I use it in 2 different components which are not depend on each other.

Method 2

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

Method 3

If you are using Redux Store, then store the socket in Redux Store and then you can access it from any component as like other store variable/state.

Component: A (Defining Socket in Component A)

//...
const dispatch = useDispatch();

useEffect(() => {
  const socket = io("http://localhost:8000");
  socket.on("connect", () => {
    console.log("Connected to Socket");
    dispatch({
      type: "INIT_SOCKET",
      socket: socket
    });
  });
}, [...]);

Component: B (Using Socket in another Component)

//...
const socket = useSelector(state => state.socket);

useEffect(() => {
  if (socket) {
    socket.on("msg", (data) => {
      console.log(data);
    });
  }
}, [socket]);

Method 4

Just declare socket outside component, same this…

import SocketIOClient from 'socket.io-client';   
const socket=SocketIOClient('http://localhost:3000/chat')

function App() {
    //use socket here ...

    return (
        <div> </div>);
}

Method 5

See react-cent
You can write your own Provider (CentProvider.js) to wrap your components and provide your client through the context. In addition, write Higher-Order Component (CentComponent.js) to make it available with this.props.<client>


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x