How to Use Socket.IO Notifications in a ReactJS Application

Published on 18 February 2023 at 17:30

Notifications are an essential part of any modern web application. They help keep users informed about important events and updates in real time. One of the most popular libraries for real-time communication between the client and the server is Socket.IO. In this blog post, we will explore how to use Socket.IO notifications in a ReactJS application.

Before we dive into the code, let's take a quick overview of Socket.IO and its features.

 

What is Socket.IO?

 

Socket.IO is a JavaScript library that enables real-time, bidirectional, and event-based communication between the client and the server. It works on every platform, browser or device, focusing equally on reliability and speed.

Socket.IO provides many features, including:

  • Real-time communication: Socket.IO enables real-time communication between the client and the server.
  • Bidirectional communication: Socket.IO allows data to be transmitted bidirectionally between the client and the server.
  • Multiple transport mechanisms: Socket.IO supports multiple transport mechanisms, including WebSocket, AJAX long polling, and more.
  • Event-based communication: Socket.IO allows event-based communication between the client and the server.

Now that we have a basic understanding of Socket.IO let's dive into the code and see how we can use Socket.IO notifications in a ReactJS application.

 

Setting up the Server

 

First, we need to set up the Socket.IO server to send notifications to our ReactJS application. We will use Node.js and the ` socket.io ` library to create our server.

  1. Install Node.js on your machine.
  2. Create a new directory and navigate to it in your terminal.
  3. Initialize a new ` Node. js ` project by running the command ` npm init ` .
  4. Install the `socket. io ` library by running the command `npm install  socket.io ` .
  5. Create a new file called `server. js ` in your project directory and add the following code:

 

const express = require('express');

const http = require('http');

const socketIo = require('socket.io');


const port = process.env.PORT || 4001 ;


const app = express();

const server = http .createServer(app);

const io = socketIo (server);


io .on ('connection', (socket) => {

   console .log( 'New client connected' );

       socket.on ('disconnect', () => {

       console .log ('Client disconnected');

   });

});
server.listen(port, () => console .log(`Listening on port ${port}`));

 

In this code, we have created an express server, added a socket.io server to it, and set up a listener for new client connections. When a client connects, the server logs a message to the console.

6. Start the server by running the command ` node server.js ` .

If you see the message "Listening on port 4001" in the console, then the server is running correctly.

 

Creating the ReactJS Application

 

Now that we have the Socket.IO server set up, we can create a ReactJS application to receive notifications from the server.

  • Create a new ReactJS project by running the command ` npx create-react-app my-app ` .
  • Navigate to the newly created project directory by running the command ` cd my-app ` .
  • Install the ` socket.io-client ` library by running the command npm install ` socket.io-client ` .
  • Open the ` src/App.js ` file and add the following code:

 

import { useState, useEffect } from 'react';

import io from 'socket.io client';
const socket = io('http://localhost:5000');


function App() {
     const [notification, setNotification] = useState('');


     useEffect(() => {
             socket.on('notification',(data)=>{

                  setNotification(data.message);

              });
     },[]);


      return (
            <div>

                    <h1>Socket.IO Notifications Example</h1>

                    {notification && <p>{notification}</p>}

            </div>

       ) ;

}

export default App;

 

In this code, we are using the useState hook to manage the notification state and the useEffect hook to listen to the notification event from the Socket.IO server. When the event is received, the setNotification function is called to update the notification state. Finally, we are rendering the notification message if it exists.

 

7. Start the ReactJS application by running the command ` npm start ` .

If everything is set up correctly, you should see the message "Socket.IO Notifications Example" and no notification messages initially.

 

Testing the Application

 

Now that we have set up the Socket.IO server and the ReactJS application, let's test it by sending a notification message from the server to the client.

  • Open the ` server.js ` file and modify the ` io.on('connection') ` function to send a notification message to the client when it connects:

 

io.on('connection', (socket) => {

   console.log('New client connected');
   socket.emit('notification', { message: 'Welcome to the Socket.IO notifications example' });
   socket.on('disconnect', () => {

       console.log('Client disconnected');

   });

});

 

In this code, we are emitting a notification event to the client with the message "Welcome to the Socket.IO notifications example" when it connects.

  • Save the ` server.js ` file and restart the server by running the command ` node server.js ` .
  • Open the ReactJS application in your browser.

If everything is working correctly, you should see the message "Welcome to the Socket.IO notifications example" displayed in the application.

 

Conclusion

 

In this blog post, we have learned how to use Socket.IO notifications in a ReactJS application. We set up a Socket.IO server and a ReactJS application and tested sending notification messages from the server to the client. We hope this tutorial has been helpful in getting you started with Socket.IO and ReactJS.

Add comment

Comments

Nick
2 years ago

This works fine. Thank you.
Now suppose i want to emit the event from the routes, how will i access the io

Rani Patel
2 years ago

ggg