DEV Community

Cover image for πŸ“‘ A Practical Guide to Using WebSockets in Real-Time Apps
Nilupul Perera
Nilupul Perera

Posted on β€’ Originally published at Medium

πŸ“‘ A Practical Guide to Using WebSockets in Real-Time Apps

In a world where users expect everything to be real-time β€” chat apps, dashboards, notifications, live updates β€” WebSockets have become a foundational tool for modern frontend developers.

If you're still relying solely on REST APIs and polling to handle dynamic data, it's time to level up. This guide will show you how to integrate WebSockets into your frontend apps in a clean, scalable, and practical way.


πŸ”„ What Are WebSockets?

WebSockets are a communication protocol that enables full-duplex, bidirectional communication between a client and server over a persistent connection.

Unlike REST or HTTP requests, WebSockets keep the connection open, allowing data to be pushed from the server without the client needing to constantly ask for updates (a.k.a. polling).


πŸš€ When Should You Use WebSockets?

Use WebSockets when you need:

  • Real-time communication (e.g., messaging, collaboration tools)
  • Live updates (e.g., stock prices, sports scores, data dashboards)
  • Push notifications without delay
  • Bidirectional interaction (e.g., multiplayer games, live auctions)

Avoid WebSockets if your app doesn't need frequent or immediate updates β€” REST may be simpler and cheaper to manage.


πŸ› οΈ Setting Up a WebSocket Server

For this example, we'll use Node.js with ws, a lightweight WebSocket library.

1. Install ws

npm install ws
Enter fullscreen mode Exit fullscreen mode

2. Create a basic WebSocket server

// server.js
const WebSocket = require('ws');

const server = new WebSocket.Server({ port: 8080 });

server.on('connection', socket => {
  console.log('Client connected');

  socket.on('message', message => {
    console.log('Received:', message);
    // Echo back
    socket.send(`Server: ${message}`);
  });

  socket.on('close', () => {
    console.log('Client disconnected');
  });
});
Enter fullscreen mode Exit fullscreen mode

🌐 Connecting WebSockets in the Frontend

Let’s connect from a React app:

// useWebSocket.js
import { useEffect, useRef } from 'react';

export default function useWebSocket(url) {
  const socketRef = useRef(null);

  useEffect(() => {
    socketRef.current = new WebSocket(url);

    socketRef.current.onopen = () => console.log('Connected');
    socketRef.current.onmessage = (event) => console.log('Message:', event.data);
    socketRef.current.onerror = (err) => console.error('WebSocket error:', err);
    socketRef.current.onclose = () => console.log('Disconnected');

    return () => socketRef.current.close();
  }, [url]);

  const sendMessage = (msg) => {
    if (socketRef.current.readyState === WebSocket.OPEN) {
      socketRef.current.send(msg);
    }
  };

  return { sendMessage };
}
Enter fullscreen mode Exit fullscreen mode

🧠 Best Practices

  • Reconnect Logic: Add automatic reconnection for dropped connections.
  • Use Context or State Management to share socket data across your app.
  • Throttle updates if you're handling high-frequency events (e.g., mouse tracking).
  • Secure Your Sockets: Use wss:// in production.
  • Fallbacks: Consider fallback strategies for older browsers or poor network conditions.

⚑ Real-World Use Case: Live Notifications

Let’s say you want to show real-time notifications in your dashboard:

  1. On server: Broadcast a "notification" event when something important happens.
  2. On client: Listen for that event and update the UI.
  3. Done β€” no polling, no delays.

πŸ“ˆ Final Thoughts

WebSockets offer a fast, efficient way to build truly interactive frontend apps. With the right architecture and tools, you can create experiences that feel instant and alive.

Don't overcomplicate it. Start small. Use a hook. Add reconnection later. Focus on user experience first.

If you're not experimenting with WebSockets yet, you're missing out on the real-time future of the web.


πŸ“Ž Save this post and follow for more frontend dev insights.

ACI image

ACI.dev: Best Open-Source Composio Alternative (AI Agent Tooling)

100% open-source tool-use platform (backend, dev portal, integration library, SDK/MCP) that connects your AI agents to 600+ tools with multi-tenant auth, granular permissions, and access through direct function calling or a unified MCP server.

Star our GitHub!

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more