26 Jan 2023

Implementing real-time notifications in a React application

Real-time notifications can be a powerful feature in any web application, allowing for immediate updates and engagement with users. In this blog post, we will explore how to implement real-time notifications in a React application using the popular library, socket.io.

First, we will start by setting up a basic React application using Create React App. Once the application is set up, we will install the socket.io library by running the command npm install socket.io in the terminal.

Next, we will create a new file called notifications.js in the src directory of our application. This file will handle all of the socket.io functionality for sending and receiving notifications. We will import the socket.io library and initialize it by connecting to a local server.

import io from 'socket.io-client';

const socket = io('http://localhost:3000');

Now that the socket is connected, we can begin implementing the functionality for sending and receiving notifications. To send a notification, we can use the emit method on the socket object, passing in the event type and the data to be sent.

socket.emit('new_notification', { message: 'Hello, world!' });

On the server side, we will listen for this event and broadcast it to all connected clients.

io.on('connection', (socket) => {
  socket.on('new_notification', (data) => {
    socket.broadcast.emit('new_notification', data);
  });
});

To receive notifications in the React application, we will create a new component called Notification that will listen for the new_notification event and display the message to the user. In the component's componentDidMount lifecycle method, we will add an event listener to the socket object.

class Notification extends React.Component {
  componentDidMount() {
    socket.on('new_notification', (data) => {
      console.log(data.message);
    });
  }

  render() {
    return null;
  }
}

We can now render this component anywhere in our application to start receiving notifications.

Finally, we will add a way for the user to dismiss notifications by adding a button to the notification component that will emit a new event, 'dismiss_notification' on the click of the button.

class Notification extends React.Component {
  componentDidMount() {
    socket.on('new_notification', (data) => {
      console.log(data.message);
    });
  }
  handleDismiss = () => {
    socket.emit('dismiss_notification', this.props.id);
  }
  render() {
    return (
        <div>
            <p>{this.props.message}</p>
            <button onClick={this.handleDismiss}>Dismiss</button>
        </div>
    );
  }
}

On the server-side, we can listen for this event and delete the notification from the database or do any other necessary cleanup.

In conclusion, implementing real-time notifications in a React application is relatively simple with the help of the socket.io library. By sending and receiving events through a socket connection, we can deliver notifications in real-time to our users. This can greatly enhance the user experience and keep them engaged with the application. We have seen how to set up a basic React application and connect it to a local server using socket.io. We have also seen how to send and receive notifications, as well as how to add a feature for dismissing notifications. With this knowledge, you can now add real-time notifications to your own React application and provide a more engaging experience for your users. Keep in mind that there are various other ways to achieve real-time notifications such as using web-sockets, server-sent events, and long-polling, each with its own advantages and disadvantages, but using socket.io is one of the most popular and easiest way to implement real-time notifications in web applications.