Socket.IO – How to implement Socket.IO in ReactJS – Part 3
Today we’ll show you how to implement Socket.IO in ReactJS. It’s the last part of the socket application where we will create a react application to listen to messages via socket.
Combining React with Socket.io for real-time application, socket.io tutorial to create a chat application, How to create a realtime app using Socket.io, React, Node, Real Time Web App | React.js + Express + Socket.io, Building Real-time ReactJS Applications with Socket.Io, How do I connect socket IO?, How do you implement WebSockets, Does socket IO use WebSocket?, Does react using WebSockets?, Building a Node.js WebSocket Chat App with Socket.io and React, react socket client using redux, react-socket-io client using hooks example.
Checkout more articles on ReactJS
We planned to divide this article into three parts.
- Part 1 – Implementation flow
- Part 2 – Implement Socket.IO in Node.js
- Part 3 – Implement Socket.IO in React (You are here…)
Way to implement Socket.IO in ReactJS
- Create react application
- Install dependency of socket
- Establish socket connection
- Manage the status of socket connection
- Subscribe to the socket event
- Handle the response coming via socket
- Output
1. Create react application
To begin the implementation, We have to start from a simple React.js application. You can use the create-react-app npm package to create a startup application. If you don’t know about it then refer to the link where you can find how to Create React Application.
2. Install dependency of socket
To implement socket in React application, we have to install socket.io-client npm package. It will help us to connect the socket using an endpoint. Run the following command to install the dependency.
1 | npm i socket.io-client |
3. Establish socket connection
After successful installation, we have to start integration of the socket in the React app. So the first step should be to establish the socket connection with help of endpoint http://localhost:4000
which we have created in the previous article Socket.IO – How to implement Socket.IO in Node.js – Part 2.
Note: Don’t forget to start the node server (http://localhost:4000
). Please check the previous article as mentioned above.
We’ll establish the socket connection in componentDidMount
method but we are using hooks so the code should look like this.
App.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | import React, { useEffect, useState } from 'react'; import io from "socket.io-client"; function App() { const [socket, setSocket] = useState(null); // establish socket connection useEffect(() => { setSocket(io('http://localhost:4000')); }, []); return ( <div> <h2>Welcome to Socket.IO App! - <a href="https://www.cluemediator.com/" target="_blank">Clue Mediator</a></h2> </div> ); } export default App; |
Here we are going to store the socket output in a state variable using react hooks.
4. Manage the status of socket connection
Now let’s manage the status of the socket connection and display status on screen. Also provide the button to connect/disconnect socket connection.
App.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | import React, { useEffect, useState } from 'react'; import io from "socket.io-client"; function App() { const [socket, setSocket] = useState(null); const [socketConnected, setSocketConnected] = useState(false); // establish socket connection useEffect(() => { setSocket(io('http://localhost:4000')); }, []); // subscribe to the socket event useEffect(() => { if (!socket) return; socket.on('connect', () => { setSocketConnected(socket.connected); }); socket.on('disconnect', () => { setSocketConnected(socket.connected); }); }, [socket]); // manage socket connection const handleSocketConnection = () => { if (socketConnected) socket.disconnect(); else { socket.connect(); } } return ( <div> <h2>Welcome to Socket.IO App! - <a href="https://www.cluemediator.com/" target="_blank">Clue Mediator</a></h2> <div> <b>Connection status:</b> {socketConnected ? 'Connected' : 'Disconnected'} </div> <input type="button" style={{ marginTop: 10 }} value={socketConnected ? 'Disconnect' : 'Connect'} onClick={handleSocketConnection} /> </div> ); } export default App; |
5. Subscribe to the socket event
Now it’s time to subscribe to the date event when socket is connected. So we can receive the message via socket.
Let’s create a function to subscribe to the event.
1 2 3 4 | // subscribe to socket date event const subscribeToDateEvent = (interval = 1000) => { socket.emit('subscribeToDateEvent', interval); } |
In the next step, call this function when the socket is connected.
1 2 3 4 5 6 7 8 9 10 11 | // subscribe to the socket event useEffect(() => { ... ... socket.on('connect', () => { ... subscribeToDateEvent(); }); ... ... }, [socket]); |
6. Handle the response coming via socket
To handle the response coming via socket, we have to listen to the socket event on getDate
and store the response in a state variable so we can display it on page.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | function App() { const [dt, setDt] = useState(''); ... ... // subscribe to the socket event useEffect(() => { ... ... socket.on("getDate", data => { setDt(data); }); }, [socket]); ... ... return ( <div> ... ... <div style={{ marginTop: 20 }}><b>Date: </b> {dt}</div> </div> ); } export default App; |
7. Output
Let’s combine all code together and see how it looks.
App.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | import React, { useEffect, useState } from 'react'; import io from "socket.io-client"; function App() { const [socket, setSocket] = useState(null); const [socketConnected, setSocketConnected] = useState(false); const [dt, setDt] = useState(''); // establish socket connection useEffect(() => { setSocket(io('http://localhost:4000')); }, []); // subscribe to the socket event useEffect(() => { if (!socket) return; socket.on('connect', () => { setSocketConnected(socket.connected); subscribeToDateEvent(); }); socket.on('disconnect', () => { setSocketConnected(socket.connected); }); socket.on("getDate", data => { setDt(data); }); }, [socket]); // manage socket connection const handleSocketConnection = () => { if (socketConnected) socket.disconnect(); else { socket.connect(); } } // subscribe to socket date event const subscribeToDateEvent = (interval = 1000) => { socket.emit('subscribeToDateEvent', interval); } return ( <div> <h2>Welcome to Socket.IO App! - <a href="https://www.cluemediator.com/" target="_blank">Clue Mediator</a></h2> <div><b>Connection status:</b> {socketConnected ? 'Connected' : 'Disconnected'}</div> <input type="button" style={{ marginTop: 10 }} value={socketConnected ? 'Disconnect' : 'Connect'} onClick={handleSocketConnection} /> <div style={{ marginTop: 20 }}><b>Date: </b> {dt}</div> </div> ); } export default App; |
That’s all about the Socket.IO application.
Thanks for reading. Happy Coding!
Thanks for the good article. Currently I am working on a project that integrates React with Redux and Node js. As I implement this method in one of my component, it seems working fine yet as soon as I unmount the component, the socket is still connected. With redux, I figured out that I have to make a socket middleware to manage socket communication even if the component is unmounted, page refresh and etc. It seems working fine with with socket middleware redux, yet I am looking forward to see what is the good way to combine socket with redux. Anyway, props to you guys, have a wonderful day!
Hello Jun,
You can handle the socket connection throughout the react application via redux. But you have to subscribe again on page reload.
Hello! thanks for reply. Well instead of using subscribe() method in store, I used useSelector() (kind of alternatives of connect() ). Do you think it is not good idea to make use of useSelector()?
Yes, The most important thing is that you have to manage the socket instance via redux.