Real-time communication is essential in modern applications, from collaborative tools to chat platforms. One of the most efficient ways to implement real-time interactions is by using WebSockets, which provide a persistent connection between the client and server for instant data exchange. In this blog post, we’ll explore how to build a simple chat application in React using WebSockets.
Prerequisites
Before starting, ensure you have the following:
1. Node.js and npm installed.
2. Basic understanding of React.
3. A text editor or IDE (e.g., VS Code).
Why WebSockets?
WebSockets enable two-way communication between a client and a server. Unlike HTTP, which follows a request-response pattern, WebSockets maintain an open connection, allowing the server to send updates to the client without waiting for a request. This makes WebSockets an ideal choice for real-time applications like chat systems.
1. Setting Up the React App
First, create a new React app using Create React App:
npx create-react-app react-chat-app
cd react-chat-app
Next, install the socket.io-client package, which simplifies WebSocket connections:
npm install socket.io-client
2. Building the WebSocket Server
We’ll create a simple WebSocket server using Node.js and socket.io.
Step 1: Set up the server
Create a new folder for the server and initialize a Node.js project:
mkdir websocket-server
cd websocket-server
npm init -y
npm install express socket.io
Step 2: Write the server code
Create a file named server.js and add the following:
const express = require("express");
const http = require("http");
const { Server } = require("socket.io");
const app = express();
const server = http.createServer(app);
const io = new Server(server, {
cors: {
origin: "http://localhost:3000", // React app URL
methods: ["GET", "POST"]
}
});
io.on("connection", (socket) => {
console.log("A user connected");
// Listen for chat messages
socket.on("chat message", (msg) => {
console.log("Message received:", msg);
io.emit("chat message", msg); // Broadcast message to all clients
});
socket.on("disconnect", () => {
console.log("A user disconnected");
});
});
server.listen(4000, () => {
console.log("WebSocket server running on port 4000");
});
Start the server with:
node server.js
The server is now ready to handle WebSocket connections!
3. Creating the Chat Component in React
Now, let’s create the chat interface in React. This will include an input for sending messages and a display area for received messages.
Step 1: Add the Chat Component
Create a new file named Chat.js in the src directory:
import React, { useState, useEffect } from "react";
import io from "socket.io-client";
// Connect to the WebSocket server
const socket = io("http://localhost:4000");
const Chat = () => {
const [messages, setMessages] = useState([]);
const [input, setInput] = useState("");
useEffect(() => {
// Listen for messages from the server
socket.on("chat message", (msg) => {
setMessages((prevMessages) => [...prevMessages, msg]);
});
return () => {
socket.off("chat message"); // Clean up the listener
};
}, []);
const sendMessage = () => {
if (input.trim()) {
socket.emit("chat message", input); // Send message to the server
setInput(""); // Clear the input field
}
};
return (
<div style={{ padding: "20px" }}>
<h1>React Chat Application</h1>
<div
style={{
border: "1px solid #ccc",
padding: "10px",
height: "300px",
overflowY: "scroll",
marginBottom: "10px"
}}
>
{messages.map((msg, index) => (
<div key={index}>{msg}</div>
))}
</div>
<input
type="text"
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="Type a message..."
style={{
padding: "10px",
width: "calc(100% - 120px)",
marginRight: "10px"
}}
/>
<button onClick={sendMessage} style={{ padding: "10px 20px" }}>
Send
</button>
</div>
);
};
export default Chat;
Step 2: Update the Main App Component
Replace the contents of App.js with:
import React from "react";
import Chat from "./Chat";
const App = () => {
return <Chat />;
};
export default App;
4. Running the Application
Start the React app:
npm start
Open the app in your browser at http://localhost:3000. You can now chat in real time! Open multiple browser tabs to simulate multiple users.
How It Works
1. Connecting to WebSocket Server:
The socket. io-client library establishes a persistent WebSocket connection to the server.
2. Sending Messages:
When a user types a message and clicks "Send," the message is emitted to the server.
3. Receiving Messages:
The server broadcasts the message to all connected clients, and each client updates its chat interface.
Conclusion
Building a real-time chat application in React using WebSockets is both fun and educational. This tutorial covered the fundamentals, from setting up a WebSocket server to building a React-based front end. With this foundation, you can expand the app to meet your specific needs.
To read more about What are the Key Features in React 19, refer to our blog What are the Key Features in React 19.