Building a Real-Time Chat App with React and Socket.io

Building a Real-Time Chat App with React and Socket.io

In this article, we will explore how to build a real-time chat app using React and Socket.io.

·

3 min read

Real-time communication is an essential feature for many web and mobile applications. With the rise of social media and messaging platforms, users expect to be able to connect and interact with each other in real-time.

In this article, we will explore how to build a real-time chat app using React and Socket.io.

What is Socket.io

Socket.io is a JavaScript library that enables real-time, bidirectional communication between web clients and servers.

It uses WebSockets to create a persistent connection between a client and a server, allowing for bi-directional communication without the need for continuous polling.

This makes it ideal for building real-time applications such as chat, gaming, and live updates.

Install socket.io

To use Socket.io, we first need to install it using npm:

npm install socket.io

Server set up

Next, we need to create a server that will handle the Socket.io connections. This can be done using Node.js and Express:

const express = require('express');
const http = require('http');
const socketio = require('socket.io');

const app = express();
const server = http.createServer(app);
const io = socketio(server);

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

With our server set up, we can now start handling Socket.io connections. Socket.io provides a number of events that can be used to handle different types of connections, such as when a client connects, disconnects, or sends a message.

To handle a new connection, we can use the connection event:

io.on('connection', (socket) => {
  console.log('New client connected');
});

To handle a client disconnection, we can use the disconnect event:

io.on('disconnection', (socket) => {
  console.log('Client disconnected');
});

Next, we need to handle messages sent by the client. To do this, we can use the message event on the client side, and the **message**event on the server side to receive and broadcast the message to all connected clients:

const express = require('express');
const http = require('http');
const socketio = require('socket.io');

const app = express();
const server = http.createServer(app);
const io = socketio(server);

io.on('connection', (socket) => {
  console.log('New client connected');

  socket.on('message', (message) => {
    io.emit('message', message);
  });

  socket.on('disconnect', () => {
    console.log('Client disconnected');
  });
});

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

React set up

With our server set up and handling connections and messages, we can now move on to the React client. To use Socket.io in our React app, we first need to install the socket.io-client library:

npm install socket.io-client

Next, we can create a component that will handle the Socket.io connection and messages. We can use the **useEffect**hook to connect to the Socket.io server when the component is mounted, and the **useState**hook to keep track of the messages and the current message being composed:

import React, { useEffect, useState } from 'react';
import io from 'socket.io-client';

const ChatApp = () => {
  const [messages, setMessages] = useState([]);
  const [currentMessage, setCurrentMessage] = useState('');

  useEffect(() => {
    const socket = io('<http://localhost:3000>');

    socket.on('connect', () => {
      console.log('Connected to Socket.io server');
    });

    socket.on('disconnect', () => {
      console.log('Disconnected from Socket.io server');
    });

    socket.on('message', (message) => {
      setMessages([...messages, message]);
    });

    return () => {
      socket.disconnect();
    };
  }, []);

  const handleSubmit = (event) => {
    event.preventDefault();

    if (currentMessage.trim() === '') {
      return;
    }

    socket.emit('message', currentMessage);
    setCurrentMessage('');
  };

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          value={currentMessage}
          onChange={(event) => setCurrentMessage(event.target.value)}
        />
        <button type="submit">Send</button>
      </form>
      <ul>
        {messages.map((message, index) => (
          <li key={index}>{message}</li>
        ))}
      </ul>
    </div>
  );
};

With our component complete, we now have a real-time chat app built with React and Socket.io. Users can connect, send and receive messages, and disconnect, all in real time.

conclusion

In conclusion, building a real-time chat app with React and Socket.io is relatively simple and can add a powerful feature to any web or mobile application. With just a few lines of code, we were able to create a fully functional chat app that allows users to connect and communicate in real-time.


Are you interested in Web development?

This Community is for you: https://discord.gg/P8bjJ7CzBV

Did you find this article valuable?

Support NFTs Lab by becoming a sponsor. Any amount is appreciated!