I'm trying to make a ReactJS realtime application with Node and Socket.IO, but I'm having a hard time figuring out the best way to handle my socket connection on the clientside.
I have multiple React components that all need some information from the server, and preferrably in realtime via the socket connection. But when importing the socket.io-client dependency and making the connection to the server in different files, I get multiple connections to the server, which doesn't really seem that optimal.
So I'm wondering if there's a better solution to share the connection between multiple components without having to create a new connection for each component. Maybe by making connection in the main app.js file and then passing it onto the child components for later use.
Some places online suggests using the context property to pass the socket variable, but React's own documentation highly discourage the use of context.
The following code is just an example, not the actual code since there's much more unnecessary code in the real project than needed to illustrate the problem.
foo.js
import React from 'react';
import io from 'socket.io-client';
const socket = io("http://localhost:3000");
class Foo extends React.Component {
// ...
componentDidMount() {
socket.on("GetFooData", (data) => {
this.setState({
fooData: data
});
});
}
// ...
}
bar.js
import React from 'react';
import io from 'socket.io-client';
const socket = io("http://localhost:3000");
class Bar extends React.Component {
// ...
componentDidMount() {
socket.on("GetBarData", (data) => {
this.setState({
barData: data
});
});
}
// ...
}
app.js
import React from 'react';
import ReactDOM from 'react-dom';
import Foo from './foo';
import Bar from './bar';
const App = () => {
return (
<div className="container">
<Foo />
<Bar />
</div>
);
};
ReactDOM.render(
<App />,
document.getElementById("root")
);