FrontendReactWebSocketsReal-TimeSocket.ioNode.js

Building Real-Time Features with React and WebSockets

Learn how to add real-time features to React applications using WebSockets — live chat, notifications, collaborative editing, and live dashboards.

Abdur Razzak

Abdur Razzak

Full-Stack Web Developer

November 30, 2024 10 min read

When Do You Need Real-Time?

Real-time features update the UI instantly when data changes on the server, without the user refreshing. Common use cases: live chat, real-time notifications, collaborative document editing, live sports scores, stock prices, and live dashboard metrics. The two main technologies for real-time are WebSockets (persistent bidirectional connection) and Server-Sent Events (SSE, server-to-client only). WebSockets are better for bidirectional communication; SSE is simpler for push notifications.

Setting Up a WebSocket Server with Node.js

Use the ws package or Socket.io for WebSocket servers in Node.js. Socket.io adds reconnection logic, room support, and fallback to long-polling, making it more robust than raw WebSockets. Install socket.io on the server and socket.io-client on the React frontend. The server emits named events with data, and clients listen for those events with socket.on('eventName', handler).

Connecting React to WebSockets

Create a custom useSocket hook that initializes the Socket.io connection once and provides socket event helpers. Use useEffect to attach event listeners and clean them up on unmount to prevent memory leaks. Keep the socket instance outside of React state to avoid unnecessary re-renders. Use React state only for the data received from socket events, not the socket connection itself.

Building a Live Chat Component

A live chat component maintains a messages array in state. When the user sends a message, emit it to the server with socket.emit('message', { text, userId, timestamp }). Listen for the 'message' event from the server to receive new messages from all users. Append new messages to the array with functional state updates. Auto-scroll to the bottom of the message list using a ref and scrollIntoView.

Real-Time Notifications

For notification systems, emit targeted events to specific users using Socket.io rooms or namespaces. On login, the user joins a room identified by their user ID. Server-side events (new order, comment, mention) emit to that specific room. On the client, show a toast notification and update the unread badge count. Persist notifications to the database so users see them after reconnecting.

Scaling WebSocket Connections

A single Node.js WebSocket server can handle thousands of connections, but horizontal scaling (multiple servers) requires a shared pub/sub layer. Use the @socket.io/redis-adapter package to broadcast events across multiple Socket.io server instances via Redis. In containerized deployments on AWS or Google Cloud, use sticky sessions to ensure a client always connects to the same server instance for the duration of their connection.

Share this article

All posts
#React#WebSockets#Real-Time#Socket.io#Node.js
Abdur Razzak — Full Stack Web Developer

Full-Stack Expert

MERN · React · Next.js · WordPress