Using Socket.IO with React
Connect to a Socket.IO server from React, listen to events, and emit messages from hooks.
Using Socket.IO with React is a free React Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the React Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Socket.IO?
Socket.IO adds rooms, namespaces, automatic reconnection, and event-based messaging on top of WebSockets with a fallback to HTTP long-polling — much more ergonomic than raw WebSocket.
Installing the Client
Install the Socket.IO client package.
npm install socket.io-clientCreating a Socket Instance
Call io(url) outside React components so the connection is shared and not recreated on every render. Export it as a singleton.
// src/lib/socket.ts
import { io } from 'socket.io-client';
export const socket = io('https://api.example.com', {
autoConnect: false, // connect manually
withCredentials: true,
});Connecting in a useEffect
Connect when the component mounts and disconnect when it unmounts to avoid dangling connections.
useEffect(() => {
socket.connect();
return () => {
socket.disconnect();
};
}, []);Listening to Events
Use socket.on('event', handler) to subscribe. Remove the listener in the cleanup function to prevent duplicate handlers on re-render.
useEffect(() => {
function onMessage(data) {
setMessages(prev => [...prev, data]);
}
socket.on('message', onMessage);
return () => {
socket.off('message', onMessage);
};
}, []);Emitting Events
Call socket.emit('event', data) to send data to the server. Optionally provide a callback (acknowledgement) as the last argument.
function sendMessage(text) {
socket.emit('message', { text, timestamp: Date.now() }, (ack) => {
console.log('Server acknowledged:', ack);
});
}Custom useSocket Hook
Encapsulate socket connection logic in a custom hook for reuse across components.
function useSocket(event, handler) {
useEffect(() => {
socket.on(event, handler);
return () => socket.off(event, handler);
}, [event, handler]);
}
// Usage:
useSocket('message', (data) => setMessages(m => [...m, data]));Rooms & Namespaces
Join a room by emitting a join event (handled server-side). Use namespaces (io('/chat')) to segment socket traffic at the connection level.
// Join a room
socket.emit('join-room', 'room-123');
// Connect to a namespace
const chatSocket = io('https://api.example.com/chat');Connection Status
Track connection state with the connect, disconnect, and connect_error events.
const [isConnected, setIsConnected] = useState(socket.connected);
useEffect(() => {
socket.on('connect', () => setIsConnected(true));
socket.on('disconnect', () => setIsConnected(false));
return () => {
socket.off('connect');
socket.off('disconnect');
};
}, []);Volatile Emits
Use socket.volatile.emit() for messages where losing occasional packets is acceptable (e.g., cursor positions, game state).
// Position updates — OK to lose some
function onMouseMove(e) {
socket.volatile.emit('cursor', { x: e.clientX, y: e.clientY });
}Socket.IO vs Raw WebSocket
Socket.IO adds room management, namespaces, auto-reconnect, and binary support on top of WebSocket. Use raw WebSocket if you need minimal overhead or the server doesn't support Socket.IO.
Quick Check
Why should you remove Socket.IO event listeners in useEffect cleanup?
Recap
Create a singleton socket instance with io(url, { autoConnect: false }). Connect/disconnect in useEffect, always remove listeners in cleanup, and emit events with socket.emit(). Encapsulate logic in a custom hook for reuse.
Frequently asked questions
Is the “Using Socket.IO with React” lesson free?
Yes — the full text of “Using Socket.IO with React” is free to read here on the web, and the React Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the React Academy course, upgrade to CoddyKit PRO.
What will I learn in “Using Socket.IO with React”?
Connect to a Socket.IO server from React, listen to events, and emit messages from hooks. You practise React Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start React Academy?
No prior experience is required. React Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Using Socket.IO with React” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this React Academy lesson?
Yes. Every React Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.