Clue Mediator

Socket.IO – How to implement Socket.IO in ReactJS – Part 3

📅March 23, 2020

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.

Way to implement Socket.IO in ReactJS

  1. Create react application
  2. Install dependency of socket
  3. Establish socket connection
  4. Manage the status of socket connection
  5. Subscribe to the socket event
  6. Handle the response coming via socket
  7. 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.

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

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

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.

// 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.

// 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.

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

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;

Output - Socket.IO – How to implement Socket.IO in ReactJS – Clue Mediator

Output - Socket.IO – How to implement Socket.IO in ReactJS – Clue Mediator

That's all about the Socket.IO application.
Thanks for reading. Happy Coding!

Demo & Source Code

Github Repository