JavaScript and React course · Module 10: React Ecosystem and Future
WebSockets and Server-Sent Events in React
In this lesson3
The station's radar has to show ship positions live. A regular REST API works like a letter: the client asks, the server answers and the conversation ends. To see changes, you would have to ask every second, wasting bandwidth and battery. Real-time communication flips this model: the server sends data by itself when something happens. In the browser you have two technologies for this: WebSocket and Server-Sent Events (SSE).
WebSockets - Two-Way Real-Time Communication
A WebSocket starts like a regular HTTP request, then switches to its own protocol (ws:// or the encrypted wss://). From that moment both sides can send text or binary messages at any time. It is the best choice for chat, live notifications, stock data and games, meaning anywhere the client also transmits often.
Basic WebSocket Implementation
The useWebSocket hook wraps the whole connection lifecycle: connecting, receiving, sending, disconnecting and retrying:
// hooks/useWebSocket.js
import { useState, useEffect, useRef, useCallback } from 'react';
const useWebSocket = (url, options = {}) => {
const [socket, setSocket] = useState(null);
const [lastMessage, setLastMessage] = useState(null);
const [readyState, setReadyState] = useState(0);
const [connectionError, setConnectionError] = useState(null);
// Socket, listeners and the retry counter in refs - changing them does not trigger a render
const socketRef = useRef(null);
const messageListeners = useRef(new Set());
const retryTimeoutRef = useRef(null);
const reconnectAttemptsRef = useRef(0);
// Latest options from the last render: callbacks passed inline
// do not change connect, so the effect does not reconnect
const optionsRef = useRef(options);
useEffect(() => {
optionsRef.current = options;
});
const { heartbeatInterval = 30000 } = options;
// Function to create connection - depends only on url
const connect = useCallback(() => {
const { protocols, reconnectAttempts = 5, reconnectInterval = 3000 } = optionsRef.current;
try {
const ws = new WebSocket(url, protocols);
socketRef.current = ws;
ws.onopen = (event) => {
console.log('WebSocket connected:', url);
setReadyState(1); // OPEN
setConnectionError(null);
reconnectAttemptsRef.current = 0;
optionsRef.current.onOpen?.(event);
};
ws.onmessage = (event) => {
let parsedData;
try {
parsedData = JSON.parse(event.data);
} catch {
parsedData = event.data;
}
setLastMessage({
data: parsedData,
timestamp: Date.now(),
raw: event.data
});
// Call all registered listeners
messageListeners.current.forEach(listener => {
listener(parsedData, event);
});
optionsRef.current.onMessage?.(parsedData, event);
};
ws.onclose = (event) => {
// Ignore events of an old socket (after reconnect or unmount)
if (socketRef.current !== ws) return;
console.log('WebSocket disconnected:', event.code, event.reason);
setReadyState(3); // CLOSED
setSocket(null);
optionsRef.current.onClose?.(event);
// Automatic reconnection
if (!event.wasClean && reconnectAttemptsRef.current < reconnectAttempts) {
reconnectAttemptsRef.current++;
console.log(`Reconnecting (${reconnectAttemptsRef.current}/${reconnectAttempts})...`);
retryTimeoutRef.current = setTimeout(() => {
connect();
}, reconnectInterval * reconnectAttemptsRef.current);
}
};
ws.onerror = (error) => {
if (socketRef.current !== ws) return;
console.error('WebSocket error:', error);
setConnectionError(error);
optionsRef.current.onError?.(error);
};
setSocket(ws);
setReadyState(0); // CONNECTING
} catch (error) {
console.error('Failed to create WebSocket:', error);
setConnectionError(error);
}
}, [url]);
// Sending messages
const sendMessage = useCallback((message) => {
const ws = socketRef.current;
if (ws && ws.readyState === WebSocket.OPEN) {
const dataToSend = typeof message === 'string' ? message : JSON.stringify(message);
ws.send(dataToSend);
return true;
} else {
console.warn('WebSocket is not connected');
return false;
}
}, []);
// Adding message listener
const addMessageListener = useCallback((listener) => {
messageListeners.current.add(listener);
return () => messageListeners.current.delete(listener);
}, []);
// Manual reconnection
const reconnect = useCallback(() => {
clearTimeout(retryTimeoutRef.current);
socketRef.current?.close();
reconnectAttemptsRef.current = 0;
connect();
}, [connect]);
// Disconnect
const disconnect = useCallback(() => {
clearTimeout(retryTimeoutRef.current);
socketRef.current?.close(1000, 'Closed by user');
}, []);
// Automatic connection on mount
useEffect(() => {
connect();
return () => {
clearTimeout(retryTimeoutRef.current);
const ws = socketRef.current;
socketRef.current = null; // the old socket's onclose will do nothing
ws?.close();
};
}, [connect]);
// Heartbeat - ping/pong
useEffect(() => {
if (socket && readyState === 1 && heartbeatInterval > 0) {
const interval = setInterval(() => {
if (socket.readyState === WebSocket.OPEN) {
sendMessage({ type: 'ping', timestamp: Date.now() });
}
}, heartbeatInterval);
return () => clearInterval(interval);
}
}, [socket, readyState, heartbeatInterval, sendMessage]);
return {
socket,
lastMessage,
readyState,
connectionError,
sendMessage,
addMessageListener,
reconnect,
disconnect,
isConnecting: readyState === 0,
isOpen: readyState === 1,
isClosing: readyState === 2,
isClosed: readyState === 3
};
};
export default useWebSocket;readyState mirrors the socket states (0 connecting, 1 open, 2 closing, 3 closed), so you get a status indicator for free. sendMessage sends only while the connection is open, and after an unclean close the hook retries with a growing delay. A heartbeat every 30 seconds sends ping, so intermediaries do not drop an idle link.
The hook avoids two traps. Callbacks such as onOpen passed inline in the chat below, and the protocols array, are new on every render, so if connect depended on them, the effect would reopen the connection after every render. That is why the hook reads the options from optionsRef, refreshed after every render, and connect depends only on url. The socket itself lives in socketRef, because otherwise the cleanup would see the socket from the render in which the effect started, which is null. The hook ignores events from an old socket, closed by reconnect or on unmount, so it will not resume the connection after you leave the chat.
Real-Time Chat
After the connection opens, ChatRoom sends a join message, and it dispatches every received message with a switch statement based on the type field:
// components/ChatRoom.jsx
import React, { useState, useEffect, useRef } from 'react';
import useWebSocket from '../hooks/useWebSocket';
const ChatRoom = ({ roomId, userId, userName }) => {
const [messages, setMessages] = useState([]);
const [newMessage, setNewMessage] = useState('');
const [typingUsers, setTypingUsers] = useState(new Set());
const [onlineUsers, setOnlineUsers] = useState(new Map());
const messagesEndRef = useRef(null);
const typingTimeoutRef = useRef(null);
const {
sendMessage,
lastMessage,
isOpen,
connectionError,
addMessageListener
} = useWebSocket(`ws://localhost:8080/chat/${roomId}`, {
onOpen: () => {
// Join room
sendMessage({
type: 'join',
roomId,
userId,
userName
});
}
});
// Handle received messages
useEffect(() => {
if (!lastMessage) return;
const { data } = lastMessage;
switch (data.type) {
case 'message':
setMessages(prev => [...prev, {
id: data.id,
text: data.text,
userId: data.userId,
userName: data.userName,
timestamp: data.timestamp
}]);
break;
case 'typing':
setTypingUsers(prev => {
const newSet = new Set(prev);
if (data.isTyping && data.userId !== userId) {
newSet.add(data.userName);
} else {
newSet.delete(data.userName);
}
return newSet;
});
break;
case 'userJoined':
setOnlineUsers(prev => new Map(prev).set(data.userId, data.userName));
setMessages(prev => [...prev, {
id: `system-${Date.now()}`,
text: `${data.userName} joined the chat`,
type: 'system',
timestamp: Date.now()
}]);
break;
case 'userLeft':
setOnlineUsers(prev => {
const newMap = new Map(prev);
newMap.delete(data.userId);
return newMap;
});
setMessages(prev => [...prev, {
id: `system-${Date.now()}`,
text: `${data.userName} left the chat`,
type: 'system',
timestamp: Date.now()
}]);
break;
case 'messageDeleted':
setMessages(prev => prev.filter(msg => msg.id !== data.messageId));
break;
case 'messageEdited':
setMessages(prev => prev.map(msg =>
msg.id === data.messageId
? { ...msg, text: data.newText, edited: true }
: msg
));
break;
}
}, [lastMessage, userId]);
// Auto-scroll to latest message
useEffect(() => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
}, [messages]);
// Sending messages
const handleSendMessage = (e) => {
e.preventDefault();
if (newMessage.trim() && isOpen) {
sendMessage({
type: 'message',
text: newMessage.trim(),
roomId,
userId,
userName
});
setNewMessage('');
handleStopTyping();
}
};
// Typing handler
const handleTyping = (e) => {
setNewMessage(e.target.value);
if (!typingTimeoutRef.current) {
sendMessage({
type: 'typing',
isTyping: true,
userId,
userName,
roomId
});
}
clearTimeout(typingTimeoutRef.current);
typingTimeoutRef.current = setTimeout(() => {
handleStopTyping();
}, 2000);
};
const handleStopTyping = () => {
if (typingTimeoutRef.current) {
clearTimeout(typingTimeoutRef.current);
typingTimeoutRef.current = null;
sendMessage({
type: 'typing',
isTyping: false,
userId,
userName,
roomId
});
}
};
// Delete message
const handleDeleteMessage = (messageId) => {
sendMessage({
type: 'deleteMessage',
messageId,
userId
});
};
if (connectionError) {
return (
<div className="chat-error">
<h3>Chat connection error</h3>
<p>{connectionError.message}</p>
<button onClick={() => window.location.reload()}>
Try again
</button>
</div>
);
}
return (
<div className="chat-room">
<div className="chat-header">
<h2>Room: {roomId}</h2>
<div className="online-users">
Online ({onlineUsers.size}): {Array.from(onlineUsers.values()).join(', ')}
</div>
<div className="connection-status">
Status: {isOpen ? 'Connected' : 'Disconnected'}
</div>
</div>
<div className="chat-messages">
{messages.map(message => (
<div
key={message.id}
className={`message ${message.type === 'system' ? 'system' : ''} ${message.userId === userId ? 'own' : ''}`}
>
{message.type !== 'system' && (
<div className="message-header">
<span className="username">{message.userName}</span>
<span className="timestamp">
{new Date(message.timestamp).toLocaleTimeString()}
</span>
{message.userId === userId && (
<button
onClick={() => handleDeleteMessage(message.id)}
className="delete-btn"
>
Delete
</button>
)}
</div>
)}
<div className="message-text">
{message.text}
{message.edited && <span className="edited"> (edited)</span>}
</div>
</div>
))}
{typingUsers.size > 0 && (
<div className="typing-indicator">
{Array.from(typingUsers).join(', ')} is typing...
</div>
)}
<div ref={messagesEndRef} />
</div>
<form onSubmit={handleSendMessage} className="chat-input">
<input
type="text"
value={newMessage}
onChange={handleTyping}
onBlur={handleStopTyping}
disabled={!isOpen}
maxLength={500}
/>
<button type="submit" disabled={!isOpen || !newMessage.trim()}>
Send
</button>
</form>
</div>
);
};
export default ChatRoom;The typing, userJoined and messageEdited types are a protocol agreed with the server, not part of the WebSocket standard. The typing indicator sends isTyping: false after two seconds of silence, so it does not flood the server with messages.
Middleware and Authorization
As the chat grows, so do the rules for messages. WebSocketMiddleware passes them through a chain of functions, like a customs officer at the airlock:
// utils/websocketMiddleware.js
class WebSocketMiddleware {
constructor() {
this.middlewares = [];
}
use(middleware) {
this.middlewares.push(middleware);
}
async processIncoming(message, socket) {
let processedMessage = message;
for (const middleware of this.middlewares) {
try {
processedMessage = await middleware.incoming(processedMessage, socket);
if (!processedMessage) break; // Middleware can stop processing
} catch (error) {
console.error('Middleware error (incoming):', error);
break;
}
}
return processedMessage;
}
async processOutgoing(message, socket) {
let processedMessage = message;
for (const middleware of this.middlewares) {
try {
processedMessage = await middleware.outgoing(processedMessage, socket);
if (!processedMessage) break;
} catch (error) {
console.error('Middleware error (outgoing):', error);
break;
}
}
return processedMessage;
}
}
// Authentication middleware
const authMiddleware = {
incoming: async (message, socket) => {
if (message.type === 'auth') {
const token = message.token;
const isValid = await validateToken(token);
if (isValid) {
socket.isAuthenticated = true;
socket.userId = getUserIdFromToken(token);
return { type: 'authSuccess', userId: socket.userId };
} else {
socket.close(4001, 'Unauthorized');
return null;
}
}
if (!socket.isAuthenticated && message.type !== 'auth') {
socket.send(JSON.stringify({
type: 'error',
message: 'Authentication required'
}));
return null;
}
return message;
},
outgoing: async (message, socket) => {
if (!socket.isAuthenticated && message.type !== 'authRequired') {
return null;
}
return message;
}
};
// Rate limiting middleware
const rateLimitMiddleware = {
incoming: async (message, socket) => {
if (!socket.messageCount) {
socket.messageCount = 0;
socket.lastReset = Date.now();
}
const now = Date.now();
const timePassed = now - socket.lastReset;
// Reset every minute
if (timePassed > 60000) {
socket.messageCount = 0;
socket.lastReset = now;
}
socket.messageCount++;
// Maximum 100 messages per minute
if (socket.messageCount > 100) {
socket.send(JSON.stringify({
type: 'error',
message: 'Rate limit exceeded'
}));
return null;
}
return message;
},
outgoing: async (message, socket) => message
};
// Hook with middleware
const useAdvancedWebSocket = (url, options = {}) => {
// Register the middleware once, on the first render (StrictMode would run an effect twice)
const middleware = useRef(null);
if (middleware.current === null) {
middleware.current = new WebSocketMiddleware();
middleware.current.use(authMiddleware);
middleware.current.use(rateLimitMiddleware);
}
const { sendMessage: baseSendMessage, socket, ...rest } = useWebSocket(url, {
...options,
onMessage: async (data, event) => {
const processed = await middleware.current.processIncoming(data, event.target);
if (processed) {
options.onMessage?.(processed, event);
}
}
});
const sendMessage = useCallback(async (message) => {
if (socket) {
const processed = await middleware.current.processOutgoing(message, socket);
if (processed) {
return baseSendMessage(processed);
}
}
return false;
}, [socket, baseSendMessage]);
return {
...rest,
sendMessage,
socket
};
};A middleware that returns null stops the message. useAdvancedWebSocket registers the middleware once, on the first render, and takes the socket from useWebSocket. Real authorization and rate limiting must still run on the server, though, because the user can change code in the browser, and on the client side such middleware only keeps traffic tidy.
Server-Sent Events (SSE) - One-Way Communication
SSE is a regular HTTP response with the text/event-stream type, which the server does not close, but keeps appending new events to. Data flows only from the server to the client, and only as text. In return, the browser's EventSource resumes a dropped connection by itself and sends the Last-Event-ID header, so no events are lost. The useServerSentEvents hook wraps it and handles named events:
// hooks/useServerSentEvents.js
import { useState, useEffect, useRef, useCallback } from 'react';
const useServerSentEvents = (url, options = {}) => {
const [data, setData] = useState(null);
const [readyState, setReadyState] = useState(0);
const [error, setError] = useState(null);
const eventSourceRef = useRef(null);
const listenersRef = useRef(new Map());
// Latest options without reconnecting, as in useWebSocket
const optionsRef = useRef(options);
useEffect(() => {
optionsRef.current = options;
});
const { withCredentials = false } = options;
const connect = useCallback(() => {
try {
const eventSource = new EventSource(url, { withCredentials });
eventSourceRef.current = eventSource;
eventSource.onopen = (event) => {
console.log('SSE connected:', url);
setReadyState(1); // OPEN
setError(null);
optionsRef.current.onOpen?.(event);
};
eventSource.onmessage = (event) => {
let parsedData;
try {
parsedData = JSON.parse(event.data);
} catch {
parsedData = event.data;
}
setData({
data: parsedData,
timestamp: Date.now(),
id: event.lastEventId,
type: event.type
});
optionsRef.current.onMessage?.(parsedData, event);
};
eventSource.onerror = (event) => {
console.error('SSE error:', event);
setReadyState(eventSource.readyState); // 0 = the browser is reconnecting, 2 = closed
setError(event);
optionsRef.current.onError?.(event);
};
// Add custom event listeners
listenersRef.current.forEach((listener, eventType) => {
eventSource.addEventListener(eventType, listener);
});
} catch (err) {
console.error('Failed to create EventSource:', err);
setError(err);
}
}, [url, withCredentials]);
const addEventListener = useCallback((eventType, listener) => {
listenersRef.current.set(eventType, listener);
if (eventSourceRef.current) {
eventSourceRef.current.addEventListener(eventType, listener);
}
return () => {
listenersRef.current.delete(eventType);
if (eventSourceRef.current) {
eventSourceRef.current.removeEventListener(eventType, listener);
}
};
}, []);
const close = useCallback(() => {
if (eventSourceRef.current) {
eventSourceRef.current.close();
eventSourceRef.current = null;
setReadyState(2);
}
}, []);
useEffect(() => {
connect();
return () => {
close();
};
}, [connect, close]);
return {
data,
readyState,
error,
addEventListener,
close,
reconnect: connect,
isConnecting: readyState === 0,
isOpen: readyState === 1,
isClosed: readyState === 2
};
};
export default useServerSentEvents;onmessage catches unnamed events, and addEventListener('metrics', ...) the ones with the event: metrics field. In onerror the hook stores eventSource.readyState: 0 means the browser is reconnecting by itself, and 2 that the connection was closed for good. Retries are decided by the browser and the retry: field sent by the server, so the hook does not count attempts itself. It reads the options from optionsRef, just like useWebSocket, so an onMessage passed inline does not reopen the connection on every render.
LiveDashboard listens for four named events: metrics, notifications, status and alerts:
// components/LiveDashboard.jsx
import React, { useState, useEffect } from 'react';
import useServerSentEvents from '../hooks/useServerSentEvents';
const LiveDashboard = () => {
const [metrics, setMetrics] = useState({
activeUsers: 0,
serverLoad: 0,
memoryUsage: 0,
requestsPerSecond: 0
});
const [notifications, setNotifications] = useState([]);
const [systemStatus, setSystemStatus] = useState('healthy');
const [lastUpdate, setLastUpdate] = useState(null);
const { data, isOpen, error, addEventListener } = useServerSentEvents(
'/api/dashboard/stream',
{
onMessage: (data) => {
setLastUpdate(new Date());
}
}
);
// Handler for different event types
useEffect(() => {
const removeMetricsListener = addEventListener('metrics', (event) => {
const metricsData = JSON.parse(event.data);
setMetrics(metricsData);
});
const removeNotificationListener = addEventListener('notification', (event) => {
const notification = JSON.parse(event.data);
setNotifications(prev => [notification, ...prev.slice(0, 9)]); // Maximum 10 notifications
});
const removeStatusListener = addEventListener('status', (event) => {
const status = JSON.parse(event.data);
setSystemStatus(status.level);
});
const removeAlertListener = addEventListener('alert', (event) => {
const alert = JSON.parse(event.data);
// Show alert as browser notification
if (Notification.permission === 'granted') {
new Notification(`System Alert: ${alert.type}`, {
body: alert.message,
icon: '/icons/alert.png'
});
}
setNotifications(prev => [{
...alert,
type: 'alert',
timestamp: Date.now()
}, ...prev.slice(0, 9)]);
});
return () => {
removeMetricsListener();
removeNotificationListener();
removeStatusListener();
removeAlertListener();
};
}, [addEventListener]);
// Ask for permission after a click: Firefox and Safari ignore a request without a user gesture
const [notificationPermission, setNotificationPermission] = useState(Notification.permission);
const requestNotifications = async () => {
setNotificationPermission(await Notification.requestPermission());
};
const getStatusColor = (status) => {
switch (status) {
case 'healthy': return '#4CAF50';
case 'warning': return '#FF9800';
case 'critical': return '#F44336';
default: return '#9E9E9E';
}
};
const getMetricColor = (value, thresholds) => {
if (value >= thresholds.critical) return '#F44336';
if (value >= thresholds.warning) return '#FF9800';
return '#4CAF50';
};
if (error) {
return (
<div className="dashboard-error">
<h2>Dashboard connection error</h2>
<p>Unable to establish connection to the monitoring server.</p>
<button onClick={() => window.location.reload()}>
Refresh page
</button>
</div>
);
}
return (
<div className="live-dashboard">
<header className="dashboard-header">
<h1>Live Dashboard</h1>
<div className="connection-info">
<span
className={`status-indicator ${isOpen ? 'connected' : 'disconnected'}`}
style={{ backgroundColor: isOpen ? '#4CAF50' : '#F44336' }}
/>
{isOpen ? 'Connected' : 'Disconnected'}
{lastUpdate && (
<span className="last-update">
Last update: {lastUpdate.toLocaleTimeString()}
</span>
)}
</div>
{notificationPermission === 'default' && (
<button onClick={requestNotifications}>Enable notifications</button>
)}
</header>
<div className="metrics-grid">
<div className="metric-card">
<h3>Active Users</h3>
<div
className="metric-value"
style={{ color: getMetricColor(metrics.activeUsers, { warning: 1000, critical: 1500 }) }}
>
{metrics.activeUsers.toLocaleString()}
</div>
</div>
<div className="metric-card">
<h3>Server Load</h3>
<div
className="metric-value"
style={{ color: getMetricColor(metrics.serverLoad, { warning: 70, critical: 90 }) }}
>
{metrics.serverLoad}%
</div>
<div className="progress-bar">
<div
className="progress-fill"
style={{
width: `${metrics.serverLoad}%`,
backgroundColor: getMetricColor(metrics.serverLoad, { warning: 70, critical: 90 })
}}
/>
</div>
</div>
<div className="metric-card">
<h3>Memory Usage</h3>
<div
className="metric-value"
style={{ color: getMetricColor(metrics.memoryUsage, { warning: 80, critical: 95 }) }}
>
{metrics.memoryUsage}%
</div>
<div className="progress-bar">
<div
className="progress-fill"
style={{
width: `${metrics.memoryUsage}%`,
backgroundColor: getMetricColor(metrics.memoryUsage, { warning: 80, critical: 95 })
}}
/>
</div>
</div>
<div className="metric-card">
<h3>Requests/sec</h3>
<div
className="metric-value"
style={{ color: getMetricColor(metrics.requestsPerSecond, { warning: 1000, critical: 2000 }) }}
>
{metrics.requestsPerSecond}
</div>
</div>
</div>
<div className="system-status">
<h3>System Status</h3>
<div
className="status-badge"
style={{
backgroundColor: getStatusColor(systemStatus),
color: 'white',
padding: '8px 16px',
borderRadius: '20px',
display: 'inline-block'
}}
>
{systemStatus.toUpperCase()}
</div>
</div>
<div className="notifications-panel">
<h3>Notifications ({notifications.length})</h3>
<div className="notifications-list">
{notifications.map((notification, index) => (
<div
key={index}
className={`notification ${notification.type || 'info'}`}
>
<div className="notification-content">
<strong>{notification.title || notification.type}</strong>
<p>{notification.message}</p>
</div>
<div className="notification-time">
{new Date(notification.timestamp).toLocaleTimeString()}
</div>
</div>
))}
</div>
</div>
</div>
);
};
export default LiveDashboard;Each listener returns a cleanup function, so the effect's cleanup detaches them all. An alert also goes to a system notification, if the user has agreed to them beforehand. A button asks for the permission, because Firefox and Safari ignore a permission request that does not come from a user gesture.
Choosing Between WebSockets and SSE
When to Use WebSockets
A collaborative editor is the textbook WebSocket case: every user transmits text changes and cursor movements, and at the same time receives everyone else's:
// Example: Real-time collaboration application
const CollaborativeEditor = () => {
const { sendMessage, lastMessage, isOpen } = useWebSocket('/ws/document/123');
const [documentContent, setDocumentContent] = useState('');
const [cursors, setCursors] = useState(new Map());
const handleTextChange = (newContent, position) => {
setDocumentContent(newContent);
// Send change to other users
sendMessage({
type: 'content_change',
content: newContent,
position,
userId: currentUser.id
});
};
const handleCursorMove = (position) => {
sendMessage({
type: 'cursor_move',
position,
userId: currentUser.id
});
};
useEffect(() => {
if (lastMessage) {
switch (lastMessage.data.type) {
case 'content_change':
setDocumentContent(lastMessage.data.content);
break;
case 'cursor_move':
setCursors(prev => new Map(prev).set(
lastMessage.data.userId,
lastMessage.data.position
));
break;
}
}
}, [lastMessage]);
return (
<div className="collaborative-editor">
{/* Editor with real-time collaboration */}
</div>
);
};Traffic flows both ways many times per second, so one persistent connection beats a series of separate HTTP requests.
When to Use SSE
A news feed is the opposite case: the reader only receives new articles, so SSE is enough:
// Example: Live news feed
const NewsFeed = () => {
const [articles, setArticles] = useState([]);
const [newArticleCount, setNewArticleCount] = useState(0);
const { data, addEventListener } = useServerSentEvents('/api/news/stream');
useEffect(() => {
const removeArticleListener = addEventListener('new_article', (event) => {
const article = JSON.parse(event.data);
setArticles(prev => [article, ...prev]);
setNewArticleCount(prev => prev + 1);
});
const removeUpdateListener = addEventListener('article_update', (event) => {
const updatedArticle = JSON.parse(event.data);
setArticles(prev => prev.map(article =>
article.id === updatedArticle.id ? updatedArticle : article
));
});
return () => {
removeArticleListener();
removeUpdateListener();
};
}, [addEventListener]);
return (
<div className="news-feed">
{newArticleCount > 0 && (
<div className="new-articles-banner">
{newArticleCount} new articles
<button onClick={() => setNewArticleCount(0)}>
Mark as read
</button>
</div>
)}
{articles.map(article => (
<ArticleCard key={article.id} article={article} />
))}
</div>
);
};There is no sendMessage here. If the client occasionally sends something, for example marks an article as read, it does so with a regular HTTP request.
Comparison and Best Practices
Finally, a helper that picks the technology based on the requirements:
// Choosing the technology based on requirements - a plain function, not a hook
const chooseTransport = ({
bidirectional = false,
authentication = false,
highFrequency = false,
binaryData = false
} = {}) =>
bidirectional || authentication || highFrequency || binaryData ? 'websocket' : 'sse';
// Each channel is a separate component that always calls the same hook
function WebSocketChannel({ url }) {
const { sendMessage, lastMessage } = useWebSocket(url.replace('http', 'ws'));
// WebSocket logic
return <div>WebSocket channel</div>;
}
function SseChannel({ url }) {
const { data, addEventListener } = useServerSentEvents(url);
// SSE logic
return <div>SSE channel</div>;
}
// Usage example
const SmartComponent = () => {
const transport = chooseTransport({
bidirectional: true, // Requires WebSocket
authentication: true
});
return transport === 'websocket'
? <WebSocketChannel url="/api/data" />
: <SseChannel url="/api/data" />;
};authentication points to WebSocket, because EventSource does not let you add custom headers, such as Authorization. The choice itself is a plain function, and the hooks are called by separate components, so each of them always calls the same hook in the same order, as the rules of hooks require. Calling useWebSocket or useServerSentEvents conditionally in a single component breaks those rules.
My advice: when data flows only from the server, start with SSE, because it is plain HTTP with automatic reconnection. Reach for WebSocket when the client also transmits often. In the exercise you will build your own hook with connecting, disconnecting, sending and a status indicator.
Remember: a WebSocket is a two-way radio channel, and SSE is a transmitter that only broadcasts - choose the one that fits the conversation.
Code for this lesson: App.jsx
import React, { useState, useEffect, useRef, useCallback } from 'react';
// WebSocket server simulation: the ship telemetry stream and replies to client commands
// Real code would use new WebSocket(url) with onopen, onmessage and onclose handlers
class MockWebSocketServer {
constructor() {
this.handlers = null;
this.openTimer = null;
this.interval = null;
}
connect(handlers) {
this.handlers = handlers;
this.openTimer = setTimeout(() => {
handlers.onOpen();
this.interval = setInterval(() => {
handlers.onMessage({
type: 'TELEMETRY',
timestamp: Date.now(),
data: {
speed: (27600 + Math.random() * 400).toFixed(0),
altitude: (408 + Math.random() * 2).toFixed(1),
fuel: (85 - Math.random() * 0.5).toFixed(1),
temperature: (20 + Math.random() * 3).toFixed(1),
oxygen: (98.5 + Math.random() * 1.5).toFixed(1),
},
});
}, 1500);
}, 400);
}
// The server replies to a client command - two-way communication
send(message) {
setTimeout(() => {
this.handlers?.onMessage({ type: 'ACK', command: message.command, timestamp: Date.now() });
}, 300);
}
// Dropped link: a close without a clean shutdown (wasClean: false)
drop() {
const handlers = this.handlers;
this.stop();
handlers?.onClose({ wasClean: false });
}
close() {
const handlers = this.handlers;
this.stop();
handlers?.onClose({ wasClean: true });
}
stop() {
clearTimeout(this.openTimer);
clearInterval(this.interval);
this.handlers = null;
}
}
// Server-Sent Events simulation: the server pushes mission notifications, the client only listens
class MockSSEServer {
subscribe(onEvent) {
const events = [
{ type: 'mission_update', data: 'Nebula mission: stage 3 completed' },
{ type: 'alert', data: 'Gravitational anomaly detected in sector 7' },
{ type: 'crew_message', data: 'Dr. Stellar: sample analysis completed' },
{ type: 'system', data: 'Navigation software update available' },
{ type: 'alert', data: 'Approaching an asteroid field - changing course' },
{ type: 'mission_update', data: 'New mission assigned: exploration of Io' },
];
let index = 0;
const interval = setInterval(() => {
const event = events[index % events.length];
index++;
onEvent({ ...event, id: index, timestamp: new Date().toLocaleTimeString('en') });
}, 2500);
return () => clearInterval(interval);
}
}
const MAX_RETRIES = 3;
const RETRY_DELAY = 2000;
// WebSocket hook: after the link drops, it tries to reconnect
// every 2 seconds, at most 3 times; a close by the user does not resume the connection
function useWebSocket() {
const [status, setStatus] = useState('DISCONNECTED');
const [messages, setMessages] = useState([]);
const [attempt, setAttempt] = useState(0);
const serverRef = useRef(null);
const retryRef = useRef({ count: 0, timer: null });
const connect = useCallback(function openConnection() {
const server = new MockWebSocketServer();
serverRef.current = server;
setStatus('CONNECTING');
server.connect({
onOpen: () => {
retryRef.current.count = 0;
setAttempt(0);
setStatus('CONNECTED');
},
onMessage: (message) => setMessages((prev) => [message, ...prev].slice(0, 20)),
onClose: ({ wasClean }) => {
serverRef.current = null;
if (wasClean || retryRef.current.count >= MAX_RETRIES) {
setStatus('DISCONNECTED');
return;
}
// Unclean close: next attempt after RETRY_DELAY
retryRef.current.count += 1;
setAttempt(retryRef.current.count);
setStatus('RECONNECTING');
retryRef.current.timer = setTimeout(openConnection, RETRY_DELAY);
},
});
}, []);
const disconnect = useCallback(() => {
clearTimeout(retryRef.current.timer);
retryRef.current.count = 0;
setAttempt(0);
if (serverRef.current) serverRef.current.close();
else setStatus('DISCONNECTED');
}, []);
const simulateDrop = useCallback(() => {
serverRef.current?.drop();
}, []);
const sendCommand = useCallback((command) => {
const message = { type: 'COMMAND', command, timestamp: Date.now() };
setMessages((prev) => [message, ...prev].slice(0, 20));
serverRef.current?.send(message);
}, []);
// Unmount: stop the server and the scheduled reconnection attempt
useEffect(() => {
const retry = retryRef.current;
return () => {
clearTimeout(retry.timer);
serverRef.current?.stop();
};
}, []);
return { status, attempt, messages, connect, disconnect, simulateDrop, sendCommand };
}
const STATUS_LABELS = {
CONNECTING: 'Connecting...',
CONNECTED: 'Connected',
RECONNECTING: 'Reconnecting',
DISCONNECTED: 'Disconnected',
};
const STATUS_COLORS = { CONNECTING: '#ffa500', CONNECTED: '#00ff88', RECONNECTING: '#ffa500', DISCONNECTED: '#ff6b6b' };
function TelemetryPanel() {
const { status, attempt, messages, connect, disconnect, simulateDrop, sendCommand } = useWebSocket();
const latest = messages.find((message) => message.type === 'TELEMETRY')?.data;
const lastAck = messages.find((message) => message.type === 'ACK');
const connected = status === 'CONNECTED';
const idle = status === 'DISCONNECTED';
const metrics = latest ? [
{ label: 'Speed', value: `${latest.speed} km/h` },
{ label: 'Altitude', value: `${latest.altitude} km` },
{ label: 'Fuel', value: `${latest.fuel}%` },
{ label: 'Temperature', value: `${latest.temperature} °C` },
{ label: 'Oxygen', value: `${latest.oxygen}%` },
] : [];
return (
<div style={styles.panel}>
<div style={styles.panelHeader}>
<h3 style={styles.heading}>WebSocket - telemetry</h3>
<div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
<span style={{ ...styles.dot, background: STATUS_COLORS[status] }} />
<span style={{ color: '#8892b0', fontSize: '12px' }}>
{STATUS_LABELS[status]}{status === 'RECONNECTING' ? ` (${attempt}/${MAX_RETRIES})` : ''}
</span>
</div>
</div>
<div style={styles.buttons}>
<button onClick={connect} disabled={!idle} style={{ ...styles.btn, opacity: idle ? 1 : 0.4 }}>Connect</button>
<button onClick={disconnect} disabled={idle} style={{ ...styles.btnDanger, opacity: idle ? 0.4 : 1 }}>Disconnect</button>
<button onClick={simulateDrop} disabled={!connected} style={{ ...styles.btnDanger, opacity: connected ? 1 : 0.4 }}>Drop the link</button>
<button onClick={() => sendCommand('PING')} disabled={!connected} style={{ ...styles.btn, opacity: connected ? 1 : 0.4 }}>Send ping</button>
</div>
{latest && (
<div style={styles.metrics}>
{metrics.map((metric) => (
<div key={metric.label} style={styles.metricCard}>
<div style={{ color: '#8892b0', fontSize: '11px' }}>{metric.label}</div>
<div style={{ color: '#00d4ff', fontSize: '17px', fontWeight: 'bold' }}>{metric.value}</div>
</div>
))}
</div>
)}
{lastAck && <p style={{ color: '#00ff88', fontSize: '12px', margin: '12px 0 0' }}>The server confirmed the {lastAck.command} command at {new Date(lastAck.timestamp).toLocaleTimeString('en')}</p>}
{!latest && idle && <p style={styles.empty}>Click "Connect" to start the data stream.</p>}
</div>
);
}
const EVENT_LABELS = { mission_update: 'mission', alert: 'alert', crew_message: 'crew', system: 'system' };
const EVENT_COLORS = { mission_update: '#00ff88', alert: '#ff6b6b', crew_message: '#ffa500', system: '#00d4ff' };
function SSENotificationsPanel() {
const [events, setEvents] = useState([]);
const [listening, setListening] = useState(false);
const unsubscribeRef = useRef(null);
const startListening = () => {
unsubscribeRef.current = new MockSSEServer().subscribe((event) => {
setEvents((prev) => [event, ...prev].slice(0, 15));
});
setListening(true);
};
const stopListening = () => {
unsubscribeRef.current?.();
unsubscribeRef.current = null;
setListening(false);
};
// Close the subscription on unmount
useEffect(() => () => unsubscribeRef.current?.(), []);
return (
<div style={styles.panel}>
<div style={styles.panelHeader}>
<h3 style={styles.heading}>SSE - notifications</h3>
<button onClick={listening ? stopListening : startListening} style={listening ? styles.btnDanger : styles.btn}>
{listening ? 'Stop' : 'Subscribe'}
</button>
</div>
<div style={{ maxHeight: '300px', overflowY: 'auto' }}>
{events.length === 0 && <p style={styles.empty}>No notifications - click "Subscribe".</p>}
{events.map((event) => (
<div key={event.id} style={{ ...styles.event, borderLeftColor: EVENT_COLORS[event.type] }}>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px' }}>
<span style={{ color: EVENT_COLORS[event.type], fontSize: '11px', textTransform: 'uppercase', fontWeight: 'bold' }}>{EVENT_LABELS[event.type]}</span>
<span style={{ color: '#8892b0', fontSize: '11px' }}>{event.timestamp}</span>
</div>
<div style={{ color: '#e0e1dd', fontSize: '13px' }}>{event.data}</div>
</div>
))}
</div>
</div>
);
}
function App() {
return (
<div style={styles.container}>
<h1 style={styles.title}>Real-time Communication Hub</h1>
<p style={styles.subtitle}>WebSockets and Server-Sent Events in React</p>
<div style={styles.grid}>
<TelemetryPanel />
<SSENotificationsPanel />
</div>
<p style={styles.note}>A WebSocket carries data both ways: the server sends telemetry, and the client sends commands such as ping. "Drop the link" shows the reconnection. SSE flows only from the server to the client, so the notifications panel sends nothing.</p>
</div>
);
}
const styles = {
container: { minHeight: '100vh', background: 'linear-gradient(135deg, #0d1b2a 0%, #1a1a3e 100%)', padding: '24px 16px', color: '#e0e1dd', fontFamily: 'system-ui, sans-serif', boxSizing: 'border-box' },
title: { textAlign: 'center', color: '#00d4ff', margin: '0 0 4px', fontSize: '24px' },
subtitle: { textAlign: 'center', color: '#8892b0', marginBottom: '20px' },
grid: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: '16px' },
panel: { background: 'rgba(0,0,0,0.3)', borderRadius: '12px', padding: '16px', border: '1px solid rgba(0,212,255,0.2)' },
panelHeader: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: '8px', flexWrap: 'wrap', marginBottom: '12px' },
heading: { color: '#00d4ff', margin: 0, fontSize: '17px' },
dot: { width: '10px', height: '10px', borderRadius: '50%', display: 'inline-block' },
buttons: { display: 'flex', gap: '8px', flexWrap: 'wrap', marginBottom: '12px' },
metrics: { display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(90px, 1fr))', gap: '8px' },
metricCard: { padding: '10px', background: 'rgba(0,212,255,0.05)', borderRadius: '8px', textAlign: 'center', border: '1px solid rgba(0,212,255,0.15)' },
event: { padding: '8px 12px', borderLeft: '3px solid', background: 'rgba(0,0,0,0.2)', marginBottom: '6px', borderRadius: '0 6px 6px 0' },
empty: { color: '#8892b0', textAlign: 'center', fontSize: '13px' },
btn: { padding: '8px 12px', background: 'rgba(0,212,255,0.15)', border: '1px solid #00d4ff', borderRadius: '6px', color: '#00d4ff', cursor: 'pointer', fontSize: '13px' },
btnDanger: { padding: '8px 12px', background: 'rgba(255,107,107,0.15)', border: '1px solid #ff6b6b', borderRadius: '6px', color: '#ff6b6b', cursor: 'pointer', fontSize: '13px' },
note: { maxWidth: '760px', margin: '16px auto 0', color: '#8892b0', fontSize: '13px', lineHeight: 1.5 },
};
export default App;Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. When is WebSocket a better choice than REST API in a React application?
2. How do Server-Sent Events (SSE) differ from WebSocket?
Hands-on tasks in the game
- Code editor
Finish the useMissionSocket hook that runs the comms channel to the station. The socket is created by createSocket(url) - in the preview it is a station simulator with the same interface as WebSocket. ___BLANK1___: in onmessage turn the text from event.data into a message object with JSON.parse. ___BLANK2___: the effect cleanup closes the socket with close() when the component goes away (also when StrictMode runs the effect twice). ___BLANK3___: send sends the object { text } turned into text with JSON.stringify. After a few seconds telemetry shows up in the preview, and every message you send comes back as an echo.