April 27, 2025
Technology
React, WebSocket

In today’s real-time web, instant communication is no longer a luxury—it’s a requirement. Whether you’re building a chat application, live feed, or collaborative platform, WebSockets are your go-to solution for real-time, bi-directional communication between the client and the server.
This article walks you through the fundamentals of WebSockets and how to implement them effectively in a React application.
WebSocket is a protocol that provides full-duplex communication channels over a single TCP connection. Unlike HTTP, which follows a request-response model, WebSocket allows both client and server to send messages to each other independently after the initial handshake.
Upgrade: websocket header.101 Switching Protocols.Let’s build a basic example of a WebSocket client in React.
First, make sure your server supports WebSockets (Node.js with ws, Python with websockets, etc.). Here’s a mock WebSocket server URL for illustration: ws://localhost:4000
// WebSocketChat.js
import React, { useEffect, useState, useRef } from 'react';
const WebSocketChat = () => {
const [messages, setMessages] = useState([]);
const [input, setInput] = useState('');
const socketRef = useRef(null);
useEffect(() => {
// Connect to the WebSocket server
socketRef.current = new WebSocket('ws://localhost:4000');
// Listen for incoming messages
socketRef.current.onmessage = (event) => {
setMessages((prev) => [...prev, event.data]);
};
// Cleanup on component unmount
return () => {
socketRef.current.close();
};
}, []);
const sendMessage = () => {
if (socketRef.current.readyState === WebSocket.OPEN) {
socketRef.current.send(input);
setInput('');
}
};
return (
<div>
<h2>WebSocket Chat</h2>
<div style={{ maxHeight: 200, overflowY: 'scroll' }}>
{messages.map((msg, idx) => (
<div key={idx}>{msg}</div>
))}
</div>
<input
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="Type message..."
/>
<button onClick={sendMessage}>Send</button>
</div>
);
};
export default WebSocketChat;
In your App.js or main component:
import React from 'react';
import WebSocketChat from './WebSocketChat';
function App() {
return (
<div>
<WebSocketChat />
</div>
);
}
export default App;
WebSocket.OPEN to check if the connection is ready before sending.wss:// in production to encrypt your WebSocket traffic.Here’s a custom React hook to abstract WebSocket logic:
import { useEffect, useRef, useState } from 'react';
export function useWebSocket(url) {
const socketRef = useRef(null);
const [messages, setMessages] = useState([]);
useEffect(() => {
socketRef.current = new WebSocket(url);
socketRef.current.onmessage = (e) => {
setMessages((prev) => [...prev, e.data]);
};
return () => socketRef.current?.close();
}, [url]);
const sendMessage = (msg) => {
if (socketRef.current?.readyState === WebSocket.OPEN) {
socketRef.current.send(msg);
}
};
return { messages, sendMessage };
}
Usage:
const { messages, sendMessage } = useWebSocket('ws://localhost:4000');
WebSockets unlock the ability to build truly interactive, real-time applications. With React’s declarative style and WebSocket’s persistent connection, you’re equipped to deliver seamless experiences to users.
By structuring your WebSocket logic cleanly—either inline or via custom hooks—you ensure scalability, maintainability, and performance.