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 (
    

Live Chat

{messages.map((msg, index) => (
{msg.message}
))}
setMessage(e.target.value)} className="border p-2 mr-2" />
); } 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