Socket Io With React

1 view
Skip to first unread message

Jule Kue

unread,
Aug 3, 2024, 4:05:04 PM8/3/24
to minsmufginktus

The hot reloading of a file that contains the initialization of a Socket.IO client (i.e. the src/socket.js file in the example above) might leave the previous Socket.IO connection alive, which means that:

We strongly advise against registering event listeners in your child components, because it ties the state of the UI with the time of reception of the events: if the component is not mounted, then some messages might be missed.

We have all encountered chat over the web, that can be Facebook, Instagram, Whatsapp and the list goes on.
Just to give a bit of context, you send a message to a person or a group, they see the message and reply back. Simple yet complex.

To develop a chat app you would need to be aware of new messages as soon as they arrive.
Usually, to get information from the server you need send an HTTP request. With websockets, the server lets you know when there is new information without asking it.

In this article, we'll leverage the real-time communication provided by Socket.io to create an open chat application that allows users to send and receive messages from several users on the application. You will also learn how to detect the users who are online and when a user is typing.

Socket.io is a popular JavaScript library that allows us to create real-time, bi-directional communication between web browsers and a Node.js server. It is a highly performant and reliable library optimized to process a large volume of data with minimal delay. It follows the WebSocket protocol and provides better functionalities, such as fallback to HTTP long-polling or automatic reconnection, which enables us to build efficient chat and real-time applications.

In this section, we'll set up the project environment for our chat application. You'll also learn how to add Socket.io to a React and Node.js application and connect both development servers for real-time communication via Socket.io.

From the code snippet above, the socket.io("connection") function establishes a connection with the React app, then creates a unique ID for each socket and logs the ID to the console whenever a user visits the web page.

? For the remaining part of this article, I will walk you through creating the web pages for the chat application and sending messages back and forth between the React app and the Node.js server. I'll also guide you on how to add the auto-scroll feature when a new message arrives and how to fetch active users in your chat application.

The code snippet assigns different routes for the Home and Chat page of the application using React Router v6 and passes the Socket.io library into the components. We'll create the Chat page in the upcoming section.

From the image above, the Chat page is divided into three sections, the Chat Bar - sidebar showing active users, the Chat Body containing the sent messages and the header, and the Chat Footer - the message box and the send button.

In this section, you'll learn how to send messages from the React app to the Node.js server and vice-versa via Socket.io. To send the messages to the server, we will need to pass the Socket.io library into the ChatFooter - component that sends the messages.

The handleSendMessage function checks if the text field is empty and if the username exists in the local storage (sign-in from the Home page) before sending the message event containing the user input, username, the message ID generated, and the socket or client ID to the Node.js server.

From the code snippet above, Socket.io listens to the messages sent via the messageResponse event and spreads the data into the messages array. The array of messages is passed into the ChatBody component for display on the UI.

socket.on("newUser") is triggered when a new user joins the chat application. The user's details (socket ID and username) are saved into the users array and sent back to the React app in a new event named newUserResponse.
In socket.io("disconnect"), the users array is updated when a user leaves the chat application, and the newUserReponse event is triggered to send the updated the list of users to the client.

From the code snippets above, lastMessageRef is attached to a div tag at the bottom of the messages, and its useEffect has a single dependency, which is the messages array. So, when the messages changes, the useEffect for the lastMessageRef re-renders.

From the code snippet above, the handleTyping function triggers the typing event whenever a user is typing into the text field. Then, we can listen to the typing event on the server and send a response containing the data to other users via another event called typingResponse.

Feel free to improve the application by adding the Socket.io private messaging feature that allows users to create private chat rooms and direct messaging, using an authentication library for user authorization and authentication and a real-time database for storage.

Socket.io is a great tool with excellent features that enables us to build efficient real-time applications like sports betting websites, auction and forex trading applications, and of course, chat applications by creating lasting connections between web browsers and a Node.js server.

The way socket.io actually works is by assuming those are AJAX requests and once some communications had been exchanged it switches the protocol, thus it's not a protocol downgrade but an upgrade (you can check that in the network tab of chrome dev tools), also check the link in the last comment for more details. Is it convenient?

Also note that socket.io has 4 different versions and both client and server need to implement the same version as far as I can remember, hence as soon as v5 appears you'll need to provide both v4 and v5 versions to avoid current clients software breaking and to provide latest stable version for new customers or customers that want to migrate (thinking on the use-case of providing just a backend as service).

It's true and not true, it's like saying that compare to the population of the world, you child will be chinese, it's most likely not true :)
So while it's true that if you target the whole world with your app that might be the case.
But try to do the same for old enterprise companies, and I promise you, you will find some Windows XP :D

I'd rather prefer the connection to be tested with the "newest" protocol and downgrade it if there's any incompatibility instead doing the opposite. It will add a delay to people with very very old devices and software and speed up the rest.

My logic is that people with very very old devices and software are already used to the slowness ?I know it by experience, had a Pentium II with a 56Kb modem for more than 10 years, on those waiting times 100-200ms won't harm much, it's a little % overall ?

Because you mentioned about browser notification, I searched in MDN if there was a tools for that purpose. So I mean like this one : developer.mozilla.org/en-US/docs/W...
Of course, you are free to use other tools, library you have found suitable for that purpose.

Nice, I am waiting for that.
Actually, I also want to see how you handle global state management if there are cases for that. Specifically, how you use Redux, because I am learning Redux with the recommended way mentioned in the Redux doc, i.e using Redux Toolkit (RTK) and RTK Query.
But it is just fine if you don't use it in that app.

In my last project, I didn't use it, because I didn't learn it, it would take longer time before I could really use it. For global state management, I used a lib named reactN by Charles Stover which was easy to use.
But now that I realize in what case Redux is suitable for, I think I am going to use it for my nearest project.

Hi, novu team.
This is so great.
I also checked your packages on github, 7.3k stars - so amzing.
Btw I want to know about nove.co platform's pricing.
This is free platform? I signed on platform but there's no payment setup.

It offers a real-time collaborative code editor featuring unique room generation, syntax highlighting, and auto-suggestions. Users can seamlessly edit, save, and download files while communicating through group chat

The HTTP protocol powers the web. Traditionally, HTTP is a request-response protocol. This means that a client requests data from a server, and the server responds to that request. In this model, a server will never send data to a client without having been queried first.

Most modern browsers nowadays support WebSockets. The WebSocket protocol builds on top of the HTTP protocol to provide a persistent bi-directional connection between the client and the server. Websockets can be used directly using JavaScript in the browser, but the API is low-level, making it complicated to create even a simple application.

The npx command is part of your Node.js installation and lets you run scripts from the npmjs repository. The express-generator script creates a new Express-based server project. The command above will create a new folder chat-server. In the terminal, navigate into that folder and install the dependencies and then some additional packages by running the following two commands.

The one dependency to note here is socket.io. This is the Socket.IO library that you will be using to provide the communication between client and server. Now, open up an editor of your choice and create a new file chat.js in the project folder. Paste the following contents into the file.

To understand this module, it is probably best to start at the bottom. The module exports a single function chat that takes the Socket.IO server instance as a parameter. When a client requests a connection, the callback will create a new Collection instance and pass the Socket.IO server instance and the new socket to the constructor. The constructor of the Connection class sets up callbacks on events coming from the socket. The disconnect and connection_error are predefined events that are triggered when the socket disconnects, or when an error happens during the connection. The message event will be triggered by the client whenever a new message has been posted in the chat. The getMessages event will be used by new clients to retrieve all existing messages from the server.

c80f0f1006
Reply all
Reply to author
Forward
0 new messages