The Power of Real-time Data Transfer of WebSockets in React

WebSocket

Nowadays WebSocket is very popular for creating applications like chat, IoT IoT-based applications.
WebSocket is a way where we can transfer data between client and server considered a two-way data transfer so it’s called Full Duplex Protocol. It has a separate design on the top of the Transfer Control Protocol (TCP).

Why WebSocket?

With the help of WebSocket, we can have bi-directional communication once the connection is established from any end without any explicit request by one or the other. They can communicate until the client or server any one of to decide terminates the connection

The main reason to use WebSocket is to get real-time data instead of fetching data from the server and called API’s to get data and use

Life Cycle of WebSocket

Life Cycle of Websocket

WebSocket Connection

Let’s see some point of WebSocket

1. Handshake

Connection is established between client and server.

2. Open and Persistent Connection

Once the connection is established communication is done in terms of bi-directional message communication.

3. Connection Closed

Once the connection is established it stays forever until the client or server wants to terminate the connection.

Now we have learned enough theory, let’s dive into the implementation. Let’s start with how we can use webSocket in react .We are implementing webSocket using functional component with the help of Hooks

Basic of WebSocket

So Let’s start with the websocket in React

  • Install websocket i.e npm i react-use-websocket
  • Create a separate file to write websocket code and import necessary import to use in your file
  • Define Url for socket

I.e const socketUrl = `wss://${serevr-end-ponit}/ws/chat/`;

const socketUrl = `wss://dev-api.urgidoctor.com/ws/chat/${appointment?.id}/`;
  • Use and define Websocket
const socket = new WebSocket(socketUrl);
  • As we are using functional components write all websocket functions in useEffect()
 useEffect(() => {
console.log("testing");
}, []);

Got a Killer Idea, Look No Further for the Perfect Support to Bring Your Vision to Life.

WebSocket Function

  • Open(): This function is used when we connect to a WebSocket through a socket URL I am directly accepting every client who wants to connect. If we want to reject a connection request, we can use socket.close().
 useEffect(() => {
socket.onopen = () => {
console.log("connected");
};
})
  • Message(): This function is used when a message is coming from the server end and here we can add our logic to store any details in DB
 socket.onmessage = e => {
const data = JSON.parse(e.data);
setMessage(data);
const text = data["message"];
};

When onmessage() calls then they give data in e and we have to parse it and use it for further operation.

  • Error(): This function will help to handle if any error occurs, we can write a logic for handling an error if it occurs during websocket communication.
socket.onerror = error => {
console.log("WebSocket Error " + error);
socket.close();
};
  • Send(): This function is used to send data or send messages to a server or other end point. Here we send data in JSON format and we can open the connection again if we close due to any reason and send a message.
socket.onopen = () => socket.send(JSON.stringify(msg_send_payload));
or
socket.send(“send message”);
  • Close(): This websocket function is used to close a connection or it calls when disconnected due to an internet connection here also we can add our logic to perform some operations.
useEffect(() => {
return () => {
socket.close();
// we can call api here if you want any
};


//eslint-disable-next-line
}, []);

That’s all! These are some basics of WebSocket in React now let’s take a Chat Application example to better understand the WebSocket in React.

Example of WebSocket

import React, { useEffect, useState, useCallback, useRef } from "react";

const socketUrl = `wss://127.0.0.1:8080'127.0.0.1:8080/ws/chat/${appointment?.id}/`;

const Chat =(postChatDetails ) => {
 const [message, setMessage] = useState([]);
 const [messages_array, setMessagesArray] = useState([]);
 const [onMessage, setOnMessage] = useState(true);
 const [sender_array, setSenderMessagesArray] = useState([]);
 const [updated_chat, setUpdatedChat] = useState([]);
useEffect(() => {
// here you can set the any previous chat history

   setUpdatedChat(messages_array);
     const parsedData = JSON.parse(postChatDetails["message"]);
 
// Login as per Requirement
     if (parsedData) {
       parsedData.map(k => {
         updated_chat.push(k);
       });

       setMessagesArray(updated_chat);
     }
   //eslint-disable-next-line
 }, []);

useEffect(() => {
// Socket connection
   socket.onopen = () => {
     console.log("connected");
   };
   socket.onmessage = e => {
     const data = JSON.parse(e.data);
     setMessage(data);
     const text = data["message"];
 
// Login as per Requirement
     if (userData?.user != text["userId"]) {
       updateState(true);
     }

     if (onMessage && userData?.user != text["userId"]) {
       if (updated_chat) {
         updated_chat.push(text);
       }
       updateMessage(updated_chat);
     }
   };
// Calls if any Error occurs and socket close 
   socket.onerror = error => {
     console.log("WebSocket Error " + error);
     socket.close();
   };
 }, []);

// I have written separate useEffect for close connection as per condition you write in previous useEffect also 
 useEffect(() => {
   return () => {
     socket.close();

     if (updatedDate && current_date && updatedDate > current_date) {
       if (updated_chat && appointment?.chat_ids) {
         updateChatDetail(appointment?.chat_ids[0]["id"], sender_array);
       }
       window.location.reload();
     }
   };

   //eslint-disable-next-line
 }, [socket.close]);

// Design will be written as you can I’m skipping design code 
 return (
     <div>
// Some code here
         <Container fluid="md">
           {messages_array &&
             messages_array?.map((test, index) => {
               return (
                 <Row key={index}>
                   <Col>
                     <div
                       style={{
                         textAlign:
                      userData?.user == test.userId ? "right" : "left",
                       }}
                     >
               <span style={{ fontSize: "13px" }}>{test.name}</span>{" "}
                       <br />
                       <span
                         style={{
                           border: "1px solid",
                           padding: "2px 15px 3px 7px",
                           borderRadius: "6px",
                           color: "var(--icon-color)",
                           fontSize: "16px",
                           overflowWrap: "break-word",
                         }}
                       >
                    {test.isDocument ? (
                           <a href={test.message} target="_blank">
                             <AppointmentIcon type="documentIconAfterCall" />
                             {test.message?.split("/")?.pop()}
                           </a>
                         ) : (
                           test.message
                         )}
                       </span>
                       <br />
                       <span style={{ fontSize: "13px" }}>
                         {message &&
                           test.dateTime &&
                           format(
                             parseDateToLocal(test.dateTime),
                             "dd MMM HH:mm a"
                           )}
                       </span>
                     </div>
                   </Col>
                 </Row>
               );
             })}
         </Container>
// Some code here
     </div>
   )
}
 export default Chat;

Output

Here is the output of websocket implementation

Likewise you can implement chat app using WebSocket , here you can proceed with more UI improvements , adding details in database etc.

coma

Conclusion

The main intention of WebSocket is to provide real-time communication between client and server as like bi-directional or two way communication. By leveraging React’s component-based architecture and virtual DOM, WebSockets seamlessly integrate with React, enabling efficient handling of asynchronous updates. The combination of React and WebSockets offers improved user experience, scalability, security, and opens up possibilities for interactive features.

Keep Reading

Keep Reading

Struggling with EHR integration? Learn about next-gen solutions in our upcoming webinar on Mar 6, at 11 AM EST.

Register Now

Let's create something together!