DEV Community

Enrique Minvielle
Enrique Minvielle

Posted on

How I Built a Real-Time Chat App with Socket.io and React

Real-time features can feel like magic, but they’re easier to build than you might think. Recently, I created a real-time chat app using Socket.io and React, and I’m excited to walk you through the process. Let’s dive in!

The Stack

  • Frontend: React for the UI.
  • Backend: Node.js with Express for the server.
  • Real-Time Magic: Socket.io for bidirectional communication.

Step 1: Setting Up the Backend

First, I initialized a Node.js server and installed the necessary packages:

npm install express socket.io
Enter fullscreen mode Exit fullscreen mode

Then, I set up a basic server with Socket.io:

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);

io.on('connection', (socket) => {
  console.log('a user connected');
  socket.on('chat message', (msg) => {
    io.emit('chat message', msg); // Broadcast the message to everyone
  });
});

server.listen(3000, () => console.log('Server running on port 3000'));
Enter fullscreen mode Exit fullscreen mode

Step 2: Building the Frontend

On the React side, I installed the Socket.io client:

npm install socket.io-client
Enter fullscreen mode Exit fullscreen mode

Then, I created a simple chat interface:

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

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

function App() {
  const [message, setMessage] = useState('');
  const [messages, setMessages] = useState([]);

  useEffect(() => {
    socket.on('chat message', (msg) => {
      setMessages((prev) => [...prev, msg]);
    });
  }, []);

  const sendMessage = () => {
    socket.emit('chat message', message);
    setMessage('');
  };

  return (
    <div>
      <ul>
        {messages.map((msg, index) => (
          <li key={index}>{msg}</li>
        ))}
      </ul>
      <input value={message} onChange={(e) => setMessage(e.target.value)} />
      <button onClick={sendMessage}>Send</button>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Step 3: Bringing It All Together

With the backend and frontend connected, I had a fully functional real-time chat app. Users could send messages instantly, and everyone in the chat would see them in real time.

Final Thoughts

Building real-time features doesn’t have to be intimidating. With tools like Socket.io and React, you can create interactive, dynamic apps in no time. What real-time features are you excited to build? Let’s chat in the comments! 🚀

Top comments (0)