Mahamudul Hasan Rubel
HomeBlogCoursesAboutProjectsSkillsExperiencePhotosContact
Mahamudul Hasan Rubel

Senior Software Engineer crafting high-performance web applications and SaaS platforms.

Navigation

  • Home
  • Blog
  • Courses
  • About
  • Projects
  • Skills
  • Experience
  • Photos
  • Contact

Get in Touch

Available for senior/lead roles and consulting.

bd.mhrubel@gmail.comHire Me

© 2026 Mahamudul Hasan Rubel. All rights reserved.

Built with using Next.js 16 & Tailwind v4

Back to Blog
Lesson 48 of the Intermediate React: Hooks, State & Data Patterns course
ReactJune 26, 20263 min read

Managing WebSocket Connections for Real-Time React Dashboards

Learn to integrate WebSockets into your React dashboard for live updates. Master connection lifecycles, message handling, and state synchronization.

ReactWebSocketsHooksReal-timePerformancejavascriptfrontend

Previously in this course, we explored managing global modals to decouple UI overlays from component trees. In this lesson, we shift our focus from static state to real-time data flow by managing WebSocket connections to keep your dashboard metrics live.

The Real-Time Challenge

While we’ve mastered the asynchronous data lifecycle using REST and React Query, those patterns are pull-based. You request data, you get data. WebSockets enable a push-based model where the server alerts your client the moment a metric changes.

Integrating this into React requires careful orchestration. Because WebSockets maintain a persistent state (the connection itself), they don't play as nicely with React's declarative re-render cycles as simple fetch requests do.

Managing WebSocket Connections with Hooks

To manage a WebSocket connection properly, we need to handle three phases:

  1. Initialization: Opening the connection when the component mounts.
  2. Event Listening: Updating state when the server pushes a message.
  3. Cleanup: Closing the connection when the component unmounts to prevent memory leaks.

Here is a robust implementation of a useWebSocket hook:

JAVASCRIPT
import { useEffect, useState, useRef } from CE9178">'react';

export const useWebSocket = (url) => {
  const [data, setData] = useState(null);
  const socketRef = useRef(null);

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

    socketRef.current.onmessage = (event) => {
      const parsedData = JSON.parse(event.data);
      setData(parsedData);
    };

    // Cleanup on unmount
    return () => {
      if (socketRef.current) {
        socketRef.current.close();
      }
    };
  }, [url]);

  return data;
};

Integrating Live Updates into the Dashboard

Now, let’s advance our running project by adding a "Live Metrics" card to the dashboard. Instead of polling the server every five seconds, we’ll use our new hook to listen for incoming updates.

JSX
const LiveMetrics = () => {
  const latestMetric = useWebSocket(CE9178">'wss://api.dashboard.com/metrics');

  if (!latestMetric) return <div>Waiting for live data...</div>;

  return (
    <div className="card">
      <h3>Live System Load</h3>
      <p>{latestMetric.value}%</p>
    </div>
  );
};

Hands-on Exercise

  1. Extend the useWebSocket hook above to include an isConnected boolean state.
  2. Update the onopen and onclose handlers to toggle this state.
  3. In your LiveMetrics component, display a "Connection Lost" warning banner if isConnected is false.

Common Pitfalls

  • Stale Closures: If your onmessage handler needs to access current state, ensure you are using the functional update pattern (setData(prev => ...)) or that the handler is recreated correctly via useCallback and added to the dependency array.
  • Reconnection Logic: Native WebSockets don't auto-reconnect. In production, you must implement a backoff strategy (e.g., trying to reconnect after 1s, then 2s, then 4s) inside the onclose event.
  • JSON Serialization: Always wrap JSON.parse in a try...catch block. Malformed messages from the server can crash your entire component tree if not handled defensively.

Recap

Managing WebSocket connections requires treating the socket instance as a persistent resource. By wrapping the lifecycle in useEffect and using useRef to hold the connection instance, we prevent unnecessary re-connections while ensuring our UI remains reactive to server-side events.

Up next: We will explore integrating WebSockets with global state management to share real-time data across multiple dashboard widgets simultaneously.

Previous lessonInternationalization Basics
Back to Blog

Similar Posts

ReactJune 25, 20263 min read

Structuring State for Performance: Optimizing React Context

Stop React performance bottlenecks caused by the Context API. Learn how to split contexts, memoize values, and prevent unnecessary re-renders in your app.

Read more
ReactPerformanceJune 26, 20263 min read

Part of the course

Intermediate React: Hooks, State & Data Patterns

intermediate · Lesson 48 of 48

  1. 1

    Mastering useRef for DOM Access

    4 min
  2. 2

    Persistent Mutable Values with useRef

    4 min
  3. 3

    Memoizing Expensive Calculations with useMemo

    3 min

Profiling with React DevTools: Identifying Performance Bottlenecks

Stop guessing why your React app is slow. Master the React Profiler to record sessions, analyze flame graphs, and pinpoint performance bottlenecks in your code.

Read more
ReactJune 26, 20264 min read

Optimizing Asset Loading: Performance, Lazy Loading, Code Splitting

Master performance optimization in React. Learn how to use lazy loading, code splitting, and image optimization to keep your dashboard fast and efficient.

Read more
4

Optimizing Function References with useCallback

3 min
  • 5

    Introduction to Custom Hooks

    4 min
  • 6

    Building a useLocalStorage Hook

    4 min
  • 7

    Refactoring Dashboard Settings

    4 min
  • 8

    Complex State with useReducer

    3 min
  • 9

    Managing Object-Based State

    3 min
  • 10

    Introduction to Context API

    3 min
  • 11

    Architecting Global State with Context and Reducer

    3 min
  • 12

    Implementing Theme Context

    4 min
  • 13

    Structuring State for Performance

    3 min
  • 14

    Handling Authentication State

    3 min
  • 15

    Integrating Reducers with Auth State

    3 min
  • 16

    Introduction to React Router

    3 min
  • 17

    Dynamic Routing with URL Parameters

    3 min
  • 18

    Nested Routes and Layouts

    4 min
  • 19

    Protected Routes for Authenticated Views

    3 min
  • 20

    Programmatic Navigation

    3 min
  • 21

    Building the Dashboard Navigation Structure

    3 min
  • 22

    Asynchronous Data Lifecycle

    3 min
  • 23

    Caching Strategies with React Query

    4 min
  • 24

    Mutations and Data Updates

    4 min
  • 25

    Synchronizing Client and Server State

    3 min
  • 26

    Integrating Live Data into the Dashboard

    3 min
  • 27

    Error Handling and Loading UI

    3 min
  • 28

    Controlled vs Uncontrolled Components

    3 min
  • 29

    Real-time Form Validation

    3 min
  • 30

    Schema-based Validation with Zod

    3 min
  • 31

    Handling Multi-step Forms

    3 min
  • 32

    Optimizing Form Submissions

    3 min
  • 33

    Performance Profiling with React DevTools

    3 min
  • 34

    Refactoring for Scalability

    3 min
  • 35

    Finalizing Dashboard Data Flow

    3 min
  • 36

    Deploying the Application

    4 min
  • 37

    Advanced Hook Composition

    3 min
  • 38

    Implementing Middleware for State

    3 min
  • 39

    Advanced Context Patterns

    3 min
  • 40

    Router Loaders and Data Prefetching

    3 min
  • 41

    Complex Route Guards

    3 min
  • 42

    Handling Large Datasets in UI

    3 min
  • 43

    Testing Hooks and Components

    3 min
  • 44

    Managing Global Modals

    4 min
  • 45

    Implementing Keyboard Shortcuts

    3 min
  • 46

    Optimizing Asset Loading

    4 min
  • 47

    Internationalization Basics

    3 min
  • 48

    Managing WebSocket Connections

    3 min
  • View full course