DEV Community

Cover image for Adding Real-Time Features to Your React App With Socket.IO
HexShift
HexShift

Posted on • Edited on

3

Adding Real-Time Features to Your React App With Socket.IO

Want to add real-time updates like chat, notifications, or live collaboration to your React application? In this tutorial, we’ll integrate Socket.IO into a React app to create a basic live message system.

Step 1: Set Up the Backend

Start with a Node.js server. Install the necessary packages:

mkdir socket-server
cd socket-server
npm init -y
npm install express socket.io

Create a file named index.js:

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",
    methods: ["GET", "POST"]
  }
});

io.on("connection", (socket) => {
  console.log("User connected:", socket.id);

  socket.on("send_message", (data) => {
    io.emit("receive_message", data);
  });

  socket.on("disconnect", () => {
    console.log("User disconnected:", socket.id);
  });
});

server.listen(4000, () => {
  console.log("Server is running on port 4000");
});

Step 2: Set Up the React Client

Now create a React app and install the client-side socket.io library:

npx create-react-app socket-client
cd socket-client
npm install socket.io-client

Step 3: Implement Messaging

In App.js:

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

const socket = io.connect("http://localhost:4000");

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

  useEffect(() => {
    socket.on("receive_message", (data) => {
      setMessages((prev) => [...prev, data]);
    });
  }, []);

  const sendMessage = () => {
    socket.emit("send_message", { message });
    setMessage("");
  };

  return (
    <div className="p-4">
      <h1 className="text-2xl font-bold mb-4">Live Chat</h1>
      <div className="space-y-2 mb-4">
        {messages.map((msg, index) => (
          <div key={index} className="p-2 bg-gray-200 rounded">{msg.message}</div>
        ))}
      </div>
      <input
        value={message}
        onChange={(e) => setMessage(e.target.value)}
        className="border p-2 mr-2"
      />
      <button onClick={sendMessage} className="bg-blue-500 text-white px-4 py-2 rounded">
        Send
      </button>
    </div>
  );
}

export default App;

Conclusion

With just a few lines of code, you’ve added real-time functionality to your app. Socket.IO makes it easy to build features that update instantly without the need to refresh the page.

For a much more extensive guide on getting the most out of React portals, check out my full 24-page PDF file on Gumroad. It's available for just $10:

Using React Portals Like a Pro.

If this post helped you, consider supporting me: buymeacoffee.com/hexshift

Tiugo image

Modular, Fast, and Built for Developers

CKEditor 5 gives you full control over your editing experience. A modular architecture means you get high performance, fewer re-renders and a setup that scales with your needs.

Start now

Top comments (0)

ACI image

ACI.dev: Fully Open-source AI Agent Tool-Use Infra (Composio Alternative)

100% open-source tool-use platform (backend, dev portal, integration library, SDK/MCP) that connects your AI agents to 600+ tools with multi-tenant auth, granular permissions, and access through direct function calling or a unified MCP server.

Check out our GitHub!

👋 Kindness is contagious

Explore this insightful write-up, celebrated by our thriving DEV Community. Developers everywhere are invited to contribute and elevate our shared expertise.

A simple "thank you" can brighten someone’s day—leave your appreciation in the comments!

On DEV, knowledge-sharing fuels our progress and strengthens our community ties. Found this useful? A quick thank you to the author makes all the difference.

Okay