WebSockets in Node.js and React: Real-Time Apps

Build real-time features with WebSockets—Socket.io, React hooks, and scaling considerations.

WebSockets enable two-way, real-time communication. Here’s how to use them with Node and React.

WebSockets and real-time
WebSockets and real-time

Backend (Node)

  • Socket.io — Library on top of WebSockets; adds rooms, fallbacks, and reconnection. Use with Express: io.on('connection', socket => { ... }). Emit to clients or rooms; handle disconnects.
  • Raw ws — Lighter weight; you implement reconnection and messaging. Use when you want minimal dependency.
  • Scaling — Sticky sessions or a pub/sub store (Redis) so multiple Node instances can broadcast. Socket.io has an adapter for Redis.

Frontend (React)

  • Connection — Open once (e.g. in a context or top-level component). Use useEffect to connect and clean up on unmount.
  • Events — Listen with socket.on('event', handler); emit with socket.emit('event', data). Store last message in state or context so UI updates.
  • Hooks — Custom hook useSocket(event) that returns latest payload and re-renders when it changes. Encapsulate connection and subscription.

Real-time feature adoption (web apps):

Apps with real-time features (%)

Use cases

Chat, live notifications, collaborative editing, dashboards. Use WebSockets when you need low-latency push from server. Use SSE or polling when one-way or simplicity is enough.

WebSockets in 100 seconds:

Takeaway

Socket.io (or ws) on Node + a React hook for subscription is a solid pattern. Plan for reconnection and scaling (Redis adapter) from the start. Prefer existing hosted services (Pusher, Ably) if you don’t want to operate the infrastructure.