← All posts

WebSockets with Node.js and React: Real-Time Without Polling

Build a WebSocket server with Node.js and the ws package, then consume it from React using a reusable custom hook — no polling, no long-polling, just a persistent bidirectional connection.

Michael Cooper5 min readGreen belt

HTTP is a request-response protocol: the client asks, the server answers, the connection closes. That works fine for most web traffic, but as soon as you need the server to push data to the client — a live feed, a chat room, collaborative editing, real-time notifications — polling becomes an expensive workaround. WebSockets give you a persistent, bidirectional channel that stays open for the life of the connection.

How the WebSocket Handshake Works

A WebSocket connection starts as an HTTP upgrade request. The client sends a standard HTTP request with an Upgrade: websocket header. If the server agrees, it responds with 101 Switching Protocols and the connection upgrades to the WebSocket protocol. From that point on, both sides can send frames at any time without the overhead of HTTP headers on each message.

The key differences from HTTP polling:

| | HTTP Polling | WebSocket | |---|---|---| | Connection | New per request | One persistent connection | | Latency | Polling interval delay | Near-instant | | Server push | Simulated | Native | | Overhead | Full HTTP headers each time | Small framing overhead |

Setting Up the Node.js Server

Install the ws package — it is the most widely used WebSocket library for Node.js:

bash
npm install ws

A minimal echo server looks like this:

js
// server.js
import { WebSocketServer, WebSocket } from 'ws'

const wss = new WebSocketServer({ port: 8080 })

wss.on('connection', (ws) => {
  console.log('client connected, total:', wss.clients.size)

  ws.on('message', (data) => {
    // echo back to the sender
    ws.send(`echo: ${data}`)
  })

  ws.on('close', () => {
    console.log('client disconnected')
  })
})

Run it with node server.js (Node 18+ supports --experimental-vm-modules for ES modules, or rename to .mjs, or add "type": "module" to package.json).

Broadcasting to All Connected Clients

For use-cases like a live ticker or a chat room you want to broadcast an incoming message to every connected client:

js
wss.on('connection', (ws) => {
  ws.on('message', (data) => {
    const text = data.toString()

    wss.clients.forEach((client) => {
      if (client.readyState === WebSocket.OPEN) {
        client.send(text)
      }
    })
  })
})

wss.clients is a Set of all active client sockets. The readyState === WebSocket.OPEN guard skips clients that are in the middle of closing. WebSocket.OPEN is the constant 1 — importing WebSocket from ws gives you access to it on the server side.

Building a useWebSocket Hook in React

On the client, the browser's native WebSocket API is all you need. Wrapping it in a hook keeps component code clean:

ts
import { useEffect, useRef, useState, useCallback } from 'react'

type Status = 'connecting' | 'open' | 'closed' | 'error'

function useWebSocket(url: string) {
  const wsRef = useRef<WebSocket | null>(null)
  const [lastMessage, setLastMessage] = useState<string | null>(null)
  const [status, setStatus] = useState<Status>('connecting')

  useEffect(() => {
    const ws = new WebSocket(url)
    wsRef.current = ws

    ws.onopen = () => setStatus('open')
    ws.onclose = () => setStatus('closed')
    ws.onerror = () => setStatus('error')
    ws.onmessage = (event) => setLastMessage(event.data)

    return () => {
      ws.close()
    }
  }, [url])

  const send = useCallback((data: string) => {
    if (wsRef.current?.readyState === WebSocket.OPEN) {
      wsRef.current.send(data)
    }
  }, [])

  return { lastMessage, status, send }
}

export default useWebSocket

A few things worth noting:

  • The effect re-runs only when url changes, so you don't get a new connection on every render.
  • send is wrapped in useCallback so it has a stable reference — safe to pass as a prop or put in a dependency array.
  • The cleanup function closes the socket when the component unmounts, preventing memory leaks.
  • wsRef holds the socket in a ref rather than state; we don't need React to re-render when the socket object itself changes, only when lastMessage or status change.

Using the Hook in a Component

tsx
import useWebSocket from './useWebSocket'

export default function LiveFeed() {
  const { lastMessage, status, send } = useWebSocket('ws://localhost:8080')

  return (
    <div>
      <p>Status: <strong>{status}</strong></p>
      <p>Last message: {lastMessage ?? 'none yet'}</p>
      <button
        onClick={() => send('ping')}
        disabled={status !== 'open'}
      >
        Send ping
      </button>
    </div>
  )
}

The button is disabled until the connection is open, so there is no race condition on the initial render.

Production Considerations

TLS: In production, serve WebSockets over wss:// (WebSocket Secure) the same way you serve https://. If you put Nginx in front of Node.js, proxy the WebSocket upgrade:

location /ws {
    proxy_pass http://localhost:8080;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "Upgrade";
    proxy_set_header Host $host;
}

Reconnection: The hook above does not automatically reconnect after a drop. For production use, add exponential backoff inside the useEffect with a setTimeout that calls new WebSocket(url) again on ws.onclose, capped at some maximum retry interval.

Scaling: A single Node.js process holds WebSocket connections in memory. If you run multiple instances behind a load balancer, wss.clients only sees clients on that one process. The standard solution is a pub/sub layer — Redis Pub/Sub is a common choice — where each process subscribes and republishes incoming messages to all its own clients.

When to Use WebSockets

WebSockets are the right tool when you need low-latency, server-initiated updates and you expect enough messages to justify keeping the connection alive. For rare push events (order shipped, CI build done), Server-Sent Events are simpler — one-directional, works over plain HTTP/2, no extra library. For strict one-request-one-response with no push requirement, plain fetch is still the right answer.

WebSockets shine for chat, multiplayer games, live collaborative editing, real-time dashboards, and anything where the server needs to push updates at a rate that would make polling impractical.