DEV Community

Cover image for Building a Real-Time Chat Application with WebSockets in React
Ayush Kumar Vishwakarma
Ayush Kumar Vishwakarma

Posted on

Building a Real-Time Chat Application with WebSockets in React

Real-time communication has become an integral feature of modern web applications, especially in chat applications. WebSockets provide a powerful way to enable real-time, bidirectional communication between a client and a server. In this guide, we’ll walk through the process of building a real-time chat application using WebSockets and React.

Prerequisites
Before diving in, ensure you have the following:

  • Basic understanding of React.
  • Node.js installed on your machine.
  • A package manager like npm or yarn.
  • Familiarity with WebSocket concepts.

Step 1: Setting Up the Backend
We need a WebSocket server to handle real-time communication. We'll use Node.js with the ws package.

  1. Initialize a Node.js project:
mkdir chat-backend  
cd chat-backend  
npm init -y  
Enter fullscreen mode Exit fullscreen mode
  1. Install the ws package:
npm install ws 
Enter fullscreen mode Exit fullscreen mode
  1. Create a WebSocket server:
// server.js  
const WebSocket = require('ws');  

const wss = new WebSocket.Server({ port: 8080 });  

wss.on('connection', (ws) => {
    console.log('Client connected');  

    ws.on('message', (message) => {
        console.log(`Received: ${message}`);  
        // Broadcast the message to all clients
        wss.clients.forEach((client) => {
            if (client.readyState === WebSocket.OPEN) {
                client.send(message);  
            }
        });
    });  

    ws.on('close', () => {
        console.log('Client disconnected');  
    });
});  

console.log('WebSocket server running on ws://localhost:8080');  
Enter fullscreen mode Exit fullscreen mode
  1. Run the server:
node server.js
Enter fullscreen mode Exit fullscreen mode

Step 2: Setting Up the React Frontend

  1. Create a new React app:
npx create-react-app chat-frontend  
cd chat-frontend  
Enter fullscreen mode Exit fullscreen mode
  1. Install dependencies for WebSocket: No additional dependencies are required as the browser's native WebSocket API will be used.

Step 3: Building the Chat Interface

  1. Create a Chat component:
// src/components/Chat.js  
import React, { useState, useEffect, useRef } from 'react';  

const Chat = () => {
    const [messages, setMessages] = useState([]);  
    const [input, setInput] = useState('');  
    const ws = useRef(null);  

    useEffect(() => {
        ws.current = new WebSocket('ws://localhost:8080');  

        ws.current.onmessage = (event) => {
            setMessages((prev) => [...prev, event.data]);  
        };  

        return () => {
            ws.current.close();  
        };
    }, []);  

    const sendMessage = () => {
        if (input.trim()) {
            ws.current.send(input);  
            setInput('');  
        }
    };  

    return (
        <div style={{ padding: '20px', maxWidth: '400px', margin: '0 auto', textAlign: 'center' }}>
            <h2>Real-Time Chat</h2>
            <div
                style={{
                    border: '1px solid #ccc',
                    borderRadius: '5px',
                    padding: '10px',
                    maxHeight: '300px',
                    overflowY: 'scroll',
                }}
            >
                {messages.map((msg, index) => (
                    <div key={index} style={{ textAlign: 'left', margin: '5px 0' }}>
                        {msg}
                    </div>
                ))}
            </div>
            <div style={{ marginTop: '10px' }}>
                <input
                    type="text"
                    value={input}
                    onChange={(e) => setInput(e.target.value)}
                    style={{
                        padding: '8px',
                        width: '70%',
                        marginRight: '5px',
                        borderRadius: '5px',
                        border: '1px solid #ccc',
                    }}
                />
                <button
                    onClick={sendMessage}
                    style={{
                        padding: '8px 12px',
                        borderRadius: '5px',
                        border: 'none',
                        backgroundColor: '#007BFF',
                        color: '#fff',
                    }}
                >
                    Send
                </button>
            </div>
        </div>
    );
};

export default Chat;  
Enter fullscreen mode Exit fullscreen mode
  1. Use the Chat component in your App.js:
import React from 'react';  
import Chat from './components/Chat';  

function App() {
    return <Chat />;  
}  

export default App;  
Enter fullscreen mode Exit fullscreen mode
  1. Start the React app:
npm start  
Enter fullscreen mode Exit fullscreen mode

Step 4: Testing the Application

  • Open your React app in multiple tabs or devices.
  • Start typing messages in one tab, and observe them appear in all connected clients in real-time!

Additional Enhancements
To make the app production-ready, consider:

  • Adding user authentication for personalized messages.
  • Integrating a database to store chat history.
  • Deploying the WebSocket server and React app to platforms like Vercel, Heroku, or AWS.

Conclusion
By leveraging WebSockets, we’ve built a lightweight, real-time chat application using React. This project demonstrates the power of WebSockets for dynamic communication, which is useful in various applications like messaging platforms, gaming, and live notifications. Dive deeper into WebSocket protocols to enhance your application further!

Happy coding! 🚀

Top comments (0)