Creating a Chat App with Socket.io and React: A Step-by-Step Guide

Hanabi Technologies
9 min readDec 7, 2023

by Vaibhav Tiwari

Have you ever wondered how to create a real-time chat app using react and socket.io? If so, you are not alone. Many developers are interested in building chat applications that can handle multiple users, messages, and rooms.

In this blog, We will show you how to create a simple chat app with react and socket.io, using some of the best practices and tools available. By the end of this blog, you will have a working chat app that you can customize and improve as you wish.

What are React and Socket.io?

Before we dive into the code, let’s briefly review what react and socket.io are, and why they are useful for creating chat apps.

React helps you make user interfaces with JavaScript. You can use it to create components that you can reuse. These components can show dynamic data and handle user actions. React also has a system to manage the state of your app. This system helps you track the changes in your data and UI.

Socket.io lets you communicate in real time between the browser and the server. It uses web sockets, a way to keep a connection open between the client and the server. This way, you can send messages without reloading the page. Socket.io also has a backup plan that uses other methods, like polling, if the browser does not support web sockets.

Together, react and socket.io make a great combination for creating chat apps, as they allow you to create responsive and interactive UIs that can communicate with the server in real time.

How to Create a Chat App with React and Socket.io?

Now that we have a basic understanding of react and socket.io, let’s see how to create a chat app with them. We will follow these steps:

  1. Set up the project and install the dependencies
  2. Create the server-side code with socket.io
  3. Create the client-side code with react
  4. Test and run the app

Step 1: Set up the project and install the dependencies

To start, we need to create a new folder for our project and initialize it with npm. Run these commands in your terminal:

mkdir chat-app
cd chat-app
npm init -y

This will create a package.json file that will store the information and dependencies of our project.

Next, we need to install the dependencies that we will use for our app. We will use the following packages:

  • express: a web framework for Node.js that will help us create the server and handle the requests
  • socket.io: the library that will enable the real-time communication between the client and the server
  • react: the library that will help us create the UI components for our app
  • react-dom: the library that will help us render the react components to the browser
  • react-scripts: a set of scripts and configurations that will help us run and build our react app
  • nodemon: a tool that will automatically restart our server whenever we make changes to the code

Run this command in your terminal to install these packages:

npm install express socket.io react react-dom react-scripts nodemon

This will create a node_modules folder that will store the installed packages and update the package.json file with the dependencies.

Step 2: Create the server-side code with socket.io

Now that we have the dependencies installed, we can start writing the code for our app. We will begin with the server-side code, which will handle the socket.io events and messages.

First, we need to create a new file called server.js in the root folder of our project. This file will contain the code for our server. Run this command in your terminal to create the file:

touch server.js

Then, open the file with your preferred code editor and add the following code:

// Import the express and socket.io modules
const express = require("express");
const socketio = require("socket.io");

// Create an express app and a server
const app = express();
const server = require("http").createServer(app);

// Create a socket.io instance and attach it to the server
const io = socketio(server);

// Define a port for the server to listen on
const PORT = process.env.PORT || 3001;

// Serve the static files from the build folder
app.use(express.static("build"));

// Handle the socket.io connection event
io.on("connection", (socket) => {
console.log("A user connected");

// Handle the socket.io join event
socket.on("join", (room) => {
console.log("A user joined the room " + room);
// Join the socket to the specified room
socket.join(room);
// Send a welcome message to the socket
socket.emit("message", {
user: "admin",
text: `Welcome to the room ${room}`,
});
// Broadcast a message to the other sockets in the room
socket.broadcast.to(room).emit("message", {
user: "admin",
text: `A new user has joined the room ${room}`,
});
});

// Handle the socket.io chat event
socket.on("chat", (data) => {
console.log("A user sent a message");
// Send the message to all the sockets in the room
io.to(data.room).emit("message", {
user: data.user,
text: data.text,
});
});

// Handle the socket.io disconnect event
socket.on("disconnect", () => {
console.log("A user disconnected");
});
});

// Start the server and listen on the port
server.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
});

Let’s break down what this code does:

  • First, we import the express and socket.io modules that we installed earlier.
  • Then, we create an express app and a server using the http module. We need to use the http module to create the server, as socket.io requires a native Node.js server to work with.
  • Next, we create a socket.io instance and attach it to the server. This will allow us to use the socket.io methods and events on the server side.
  • After that, we define a port for the server to listen on. We use the process.env.PORT variable to get the port from the environment, or default to 3001 if it is not defined. This will help us deploy the app to a hosting service later.
  • Then, we use the express.static middleware to serve the static files from the build folder. The build folder will contain the compiled and optimized react code that we will create later. This will allow us to serve both the server and the client from the same port.
  • Next, we handle the socket.io connection event, which is triggered when a client connects to the server. We use a callback function that takes a socket parameter, which represents the individual connection between the client and the server. Inside the callback, we can use the socket methods and events to communicate with the client.
  • Inside the connection event, we handle the following events:
  1. The join event is triggered when a client joins a room. We use the socket.join method to add the socket to the specified room, and the socket. emit and socket.broadcast methods to send messages to the socket and the other sockets in the room, respectively. A room is a logical grouping of sockets that can communicate with each other. We will use the room name as the chat room name in our app.
  2. The chat event is triggered when a client sends a message. We use the io. to method to send the message to all the sockets in the room, including the sender. The data parameter contains the user name, the message text, and the room name of the sender.
  3. The disconnect event is triggered when a client disconnects from the server. We can use this event to perform any cleanup or notification tasks.
  • Finally, we start the server and listen to the port using the server. listen method. We also log a message to the console to indicate that the server is running.

That’s it for the server-side code. We have created a simple server that can handle the socket.io events and messages for our chat app.

Step 3: Create the client-side code with react

Now that we have the server-side code ready, we can move on to the client-side code, which will create the UI components for our chat app.

First, we need to create a new folder called client in the root folder of our project. This folder will contain the react code for our app. To create the folder, run the following command in your terminal:

mkdir client

Then, we need to initialize the react app inside the client folder using the create-react-app tool. This tool will set up the basic structure and configuration for our react app. To initialize the react app, run the following command in your terminal:

npx create-react-app client

This will create a new folder called client with the following files and folders:

  • node_modules: the folder that contains the react dependencies
  • public: the folder that contains the public files, such as the index.html file and the favicon
  • src: the folder that contains the source code for our react app
  • package.json: the file that contains the information and dependencies

Step 4: Test and run the app

Now that we have the code for both the server and the client, we can test and run the app. To do that, we need to follow these steps:

  • First, we need to build the react app and create the build folder that contains the optimized and compiled code. To do that, run the following command in your terminal from the client folder:
npm run build

This will create a build folder inside the client folder that will contain the static files for our app.

  • Next, we need to start the server and serve the app. To do that, run the following command in your terminal from the root folder of the project:
npm run start

This will start the server and serve the app on the port 3001. You can also use the nodemon command to start the server with automatic reloading:

npm run dev
  • Finally, we need to open the app in the browser and test it. To do that, open your browser and go to the following URL:
http://localhost:3001

This will open the app in your browser.

You can enter your name and the room name and join the chat. You can also open another tab or window and join the same or a different room with another name. You should be able to see the messages from the other users in real-time.

Congratulations, you have created a chat app with react and socket.io!

Step 5: Add some features and improvements to the app

The chat app we have created is very basic and has a lot of room for improvement. Here are some of the features and enhancements that you can add to the app:

  • Add a user list: You can add a user list component that shows the names of the users who are currently in the room. You can use the socket.io method to keep track of the users who join and leave the room and update the user list accordingly.
  • Add a message input: You can add a message input component that allows the user to type and send messages. You can also add some features like an emoji picker, file upload, or voice input to make the message input more interactive and fun.
  • Add a message list: You can add a message list component that shows the messages from the users in the room. You can also add some features like message timestamp, message status, or message reactions to make the message list more informative and engaging.
  • Add a room list: You can add a room list component that shows the names of the rooms that are available or created by the users. You can also add some features like room creation, room deletion, or room joining to make the room list more dynamic and user-friendly.
  • Add some styles and animations: You can add some styles and animations to the app to make it more attractive and appealing. You can use CSS or any UI library or framework to style the components and add some transitions and effects to the app.

These are just some of the ideas that you can implement to improve the app. You can also come up with ideas and features that you think will make the app better and more enjoyable.

Conclusion

In this blog, we have learned how to create a chat app with react and socket.io. We have seen how to set up the project and install the dependencies, how to create the server-side code with socket.io, how to create the client-side code with react, and how to test and run the app. We have also seen some of the features and improvements that we can add to the app to make it more awesome.

We hope that you have enjoyed this blog and learned something new and useful.

Thank you for reading and happy coding!

--

--

Hanabi Technologies
Hanabi Technologies

Written by Hanabi Technologies

INSPIRED BY THE JAPANESE CULTURE OF IKIGAI 生き甲斐 — Software is out passion, DRIVEN BY THE JAPANESE PRINCIPAL OF KAIZEN 改善, かいぜん — Continuous improvement

No responses yet