MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
WebSockets Architecture with Socket.io in React0%
Study Materials
React.js for AdvancedProgress 0%
1.1Control Props and Inversion of Control Pattern1.2State Reducer Pattern in Advanced React1.3Prop Getters and Flexible Design Systems1.4Headless UI Architecture and Accessibility Primitives
14.1WebSockets Architecture with Socket.io in React14.2Server-Sent Events (SSE) for Real-Time Streaming14.3Building a Collaborative Multi-User Canvas
HomeTutorialsReact.js for AdvancedWebSockets Architecture with Socket.io in React
Server-Sent Events (SSE) for Real-Time Streaming

WebSockets Architecture with Socket.io in React

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

Building collaborative real-time web applications—such as enterprise team chats, live trading dashboards, or multiplayer canvases—requires low-latency bidirectional communication. While raw browser WebSocket APIs lack automatic reconnection, rooms, and heartbeat acknowledgments, Socket.io provides a battle-tested enterprise framework for real-time React applications.


1. Raw WebSockets vs Socket.io

FeatureRaw WebSockets (new WebSocket())Socket.io (socket.io-client)
ProtocolStandard RFC 6455Custom framing built atop Engine.IO
FallbackFails if WebSockets are blocked by proxiesAutomatic fallback to HTTP long-polling
ReconnectionMust be coded manuallyAutomatic exponential backoff reconnection
MultiplexingSingle channelNamespaces and Rooms
AcknowledgementsManual correlation IDsBuilt-in callback acknowledgments

2. Singleton Socket Pattern in React

Creating a new socket connection inside a component causes multiple duplicate connections whenever components re-render or mount. Instead, maintain a singleton socket instance or wrap it in a dedicated React Context:

1// src/context/SocketContext.tsx
2import React, { createContext, useContext, useEffect, useState } from "react";
3import { io, Socket } from "socket.io-client";
4 
5const SOCKET_SERVER_URL = "https://realtime.enterprise.com";
6 
7const SocketContext = createContext<Socket | null>(null);
8 
9export function SocketProvider({ children }: { children: React.ReactNode }) {
10 const [socket, setSocket] = useState<Socket | null>(null);
11 
12 useEffect(() => {
13 // 1. Initialize client singleton
14 const socketInstance = io(SOCKET_SERVER_URL, {
15 autoConnect: true,
16 reconnectionAttempts: 5,
17 reconnectionDelay: 1000,
18 transports: ["websocket", "polling"], // Attempt WebSocket first, fallback to polling
19 auth: {
20 token: sessionStorage.getItem("access_token"),
21 },
22 });
23 
24 socketInstance.on("connect", () => {
25 console.log("Socket connected:", socketInstance.id);
26 });
27 
28 socketInstance.on("connect_error", (err) => {
29 console.error("Socket connection error:", err.message);
30 });
31 
32 setSocket(socketInstance);
33 
34 return () => {
35 // 2. Disconnect cleanly when provider unmounts
36 socketInstance.disconnect();
37 };
38 }, []);
39 
40 return (
41 <SocketContext.Provider value={socket}>
42 {children}
43 </SocketContext.Provider>
44 );
45}
46 
47export const useSocket = () => useContext(SocketContext);

3. Real-Time Chat Room Component

1import React, { useEffect, useState } from "react";
2import { useSocket } from "../context/SocketContext";
3 
4interface ChatMessage {
5 id: string;
6 sender: string;
7 text: string;
8 timestamp: string;
9}
10 
11export function EnterpriseChatRoom({ roomId }: { roomId: string }) {
12 const socket = useSocket();
13 const [messages, setMessages] = useState<ChatMessage[]>([]);
14 const [inputMessage, setInputMessage] = useState("");
15 
16 useEffect(() => {
17 if (!socket) return;
18 
19 // Join room channel
20 socket.emit("room:join", { roomId });
21 
22 // Listener for incoming broadcasts
23 const handleNewMessage = (message: ChatMessage) => {
24 setMessages((prev) => [...prev, message]);
25 };
26 
27 socket.on("message:received", handleNewMessage);
28 
29 return () => {
30 // MANDATORY: Remove specific event listener to prevent duplicate listeners
31 socket.off("message:received", handleNewMessage);
32 socket.emit("room:leave", { roomId });
33 };
34 }, [socket, roomId]);
35 
36 const sendMessage = (e: React.FormEvent) => {
37 e.preventDefault();
38 if (!socket || !inputMessage.trim()) return;
39 
40 // Emit event with server acknowledgment callback
41 socket.emit(
42 "message:send",
43 { roomId, text: inputMessage },
44 (ack: { status: string; messageId: string }) => {
45 if (ack.status === "OK") {
46 setInputMessage("");
47 }
48 }
49 );
50 };
51 
52 return (
53 <div className="flex flex-col h-[500px] max-w-lg bg-slate-900 border border-slate-800 rounded-xl overflow-hidden text-white">
54 <header className="p-4 bg-slate-950 border-b border-slate-800 font-bold text-sm">
55 Channel #{roomId}
56 </header>
57 
58 <div className="flex-1 p-4 overflow-y-auto space-y-3">
59 {messages.map((msg) => (
60 <div key={msg.id} className="p-2.5 bg-slate-800/60 rounded-lg text-xs">
61 <span className="font-semibold text-cyan-400 block">{msg.sender}</span>
62 <p className="mt-0.5 text-slate-200">{msg.text}</p>
63 </div>
64 ))}
65 </div>
66 
67 <form onSubmit={sendMessage} className="p-3 bg-slate-950 border-t border-slate-800 flex gap-2">
68 <input
69 type="text"
70 value={inputMessage}
71 onChange={(e) => setInputMessage(e.target.value)}
72 placeholder="Type message..."
73 className="flex-1 px-3 py-1.5 bg-slate-800 border border-slate-700 rounded text-xs text-white focus:outline-none focus:ring-2 focus:ring-cyan-500"
74 />
75 <button type="submit" className="px-4 py-1.5 bg-cyan-600 hover:bg-cyan-500 font-semibold rounded text-xs">
76 Send
77 </button>
78 </form>
79 </div>
80 );
81}

4. The Critical Rule: Listener Teardown with socket.off

Failing to call socket.off("event", handler) in useEffect cleanup causes listener leaks. Every time the component re-renders or mounts, an additional duplicate listener is registered. If the component mounts 5 times, a single incoming message triggers the state setter 5 times, duplicating messages in the UI!


Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
Why is creating new Socket.io instances directly inside component bodies considered an anti-pattern?
Question 2
What does calling socket.off("eventName", handler) in the useEffect cleanup achieve?
Question 3
What advantage does Socket.io have over raw WebSockets when navigating corporate firewalls?
Question 4
How do built-in acknowledgments work in Socket.io?
Question 5
What is the purpose of Socket.io "Rooms"?
Next Lesson

Server-Sent Events (SSE) for Real-Time Streaming

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Real-Time GraphQL Subscriptions with WebSocketsServer-Sent Events (SSE) for Real-Time Streaming

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master React.js for Advanced with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext