Building a Real-Time Chat App with Socket.IO and React

Rind Devran Tukan
Rind Devran Tukan
< 1 min read
Real-time chat app with Socket.IO
Reading Time: < 1 minute

Project Overview

This tutorial demonstrates how to build a real-time chat application using Socket.IO and React.

Backend Setup

const express = require('express');
const socketIO = require('socket.io');

const app = express();
const server = app.listen(4000, () => {
  console.log('Server running on port 4000');
});

const io = socketIO(server);

io.on('connection', (socket) => {
  socket.on('message', (msg) => {
    io.emit('message', msg);
  });
});

Frontend with React

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

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

function ChatApp() {
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');

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

  const sendMessage = () => {
    socket.emit('message', input);
    setInput('');
  };

  return (
    <div>
      <div>
        {messages.map((msg, i) => (
          <p key={i}>{msg}</p>
        ))}
      </div>
      <input value={input} onChange={(e) => setInput(e.target.value)} />
      <button onClick={sendMessage}>Send</button>
    </div>
  );
}

Conclusion

You now have a fully functional real-time chat application!

Related Articles

Discover more stories from our blog