Skip to content
PD
All insights

WebSockets in React: A Practical Guide

Learn how to implement real-time communication in React using WebSockets. This guide covers setup, integration, and practical examples to build responsive web apps.

WebSockets in React: A Practical Guide

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.


What is WebSocket?

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.

Key Features:
  • Persistent connection
  • Low latency communication
  • Reduced overhead (no HTTP headers after handshake)
  • Ideal for real-time apps like chats, live updates, and online gaming

How WebSockets Work
  1. Handshake: The client sends an HTTP request with an Upgrade: websocket header.
  2. Upgrade: If the server supports WebSockets, it responds with 101 Switching Protocols.
  3. Communication: A persistent connection is established. Both parties can now send messages at will.

Implementing WebSocket in React

Let’s build a basic example of a WebSocket client in React.

Setup

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

1. Create a React Component
// 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;

2. Include the Component

In your App.js or main component:

import React from 'react';
import WebSocketChat from './WebSocketChat';

function App() {
  return (
    <div>
      <WebSocketChat />
    </div>
  );
}

export default App;

Tips and Best Practices

  • Connection management: Use WebSocket.OPEN to check if the connection is ready before sending.
  • Reconnection logic: Implement automatic reconnection if the socket closes unexpectedly.
  • Debounce and throttle: Prevent flooding the server with too many messages.
  • Security: Always use wss:// in production to encrypt your WebSocket traffic.

Bonus: WebSocket with Custom Hook

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.

// Article tags

// More insights

WebSockets in React: A Practical Guide | Prabhat Dawadi