Understanding and Implementing the Custom React Hook for Network State Monitoring

Apr 19, 2024

Understanding and Implementing the Custom React Hook for Network State Monitoring

This blog post delves into the implementation of a custom React hook named useNetworkState. Understand its functionality, purpose, and how to integrate it into your React applications for effective network state management.

Subject Matter Expert

Tarun Bhagchand Soni
Tarun Bhagchand SoniSenior Software Engineer - II
Network Status- Stack Blitz
Click On the Image Above To See How It Works


What is the useNetworkState Hook?

The useNetworkState hook is a custom React hook designed to monitor the user's online/offline status and provide relevant information within your React components. It utilizes the browser's navigator.onLine property to determine the current network state and maintains its own state within the hook using the useState hook.

import { useState, useEffect, useCallback } from "react";

type NetworkState = {
  online: boolean;
  error?: string;
};

const useNetworkState = (): NetworkState => {
  const [networkState, setNetworkState] = useState<NetworkState>({
    online: navigator.onLine,
    error: undefined,
  });

  const updateNetworkState = useCallback(() => {
    try {
      setNetworkState(prevState => ({
        ...prevState,
        online: navigator.onLine,
        error: undefined,
      }));
    } catch (error) {
      console.error("Error updating network state:", error);
      setNetworkState(prevState => ({
        ...prevState,
        error: "Error updating network state",
      }));
    }
  }, []);

  useEffect(() => {
    window.addEventListener("online", updateNetworkState);
    window.addEventListener("offline", updateNetworkState);

    updateNetworkState();

    return () => {
      window.removeEventListener("online", updateNetworkState);
      window.removeEventListener("offline", updateNetworkState);
    };
  }, [updateNetworkState]);

  return networkState;
};

export default useNetworkState;


Breakdown of the Code

Let us dissect the individual parts of the useNetworkState hook:

  1. State Definition:
    • The hook starts by defining a type alias named NetworkState to represent the structure of the data it will manage. This type includes two properties:
      • online: A boolean value indicating the current online status (true if online, false if offline).
      • error: An optional string value to store any potential error messages during state updates.
    • The useState hook is used to create a state variable named networkState with the initial value set based on the current navigator.onLine property. This ensures the hook reflects the initial network state upon first render.
  2. updateNetworkState Function:
    • This function, declared using useCallback, is responsible for updating the networkState based on the current online status. It performs the following actions:
      • Attempts to update the online property of the state with the current navigator.onLine value.
      • If any error occurs during the update, it logs the error message and sets the error property of the state with a generic error message.
  3. useEffect Hook:
    • This hook manages the lifecycle of event listeners and state updates related to network changes. It performs the following actions:
      • Adds event listeners for both "online" and "offline" events to the window object, triggering the updateNetworkState function whenever the network status changes.
      • Calls the updateNetworkState function immediately after the useEffect hook runs to ensure the state reflects the initial network status.
      • In the cleanup function returned by useEffect, removes the event listeners when the component unmounts to prevent memory leaks and unnecessary event handling.
  4. Returning the State:
    • The hook simply returns the current value of the networkState object, allowing components that use this hook to access the online and error properties for further processing and UI updates.


Using the useNetworkState Hook in Your Components

To utilize the useNetworkState hook in your React components, follow these steps:

  • Import the Hook:

JavaScript

import useNetworkState from './path/to/useNetworkState';

  • Call the Hook and Access the State:

JavaScript

const { online, error } = useNetworkState();

// Use the online and error values in your component's logic and UI

For example, you can conditionally render different UI elements based on the online state or display an error message if the error property is populated.

Hire Us Form


Conclusion

The useNetworkState hook demonstrates the power of custom hooks in managing application-specific logic within React components. By encapsulating the network state management and providing a clean interface, this hook simplifies the development process and promotes code reusability. You can further enhance this hook by adding features like debouncing the state updates to avoid excessive re-renders or implementing more specific error handling based on the error types.

Subscribe to Our Newsletter

More from the engineering frontline.

Dive deep into our research and insights on design, development, and the impact of various trends to businesses.
Insight
Taming Elasticsearch at Scale
Oct 13, 2026

Taming Elasticsearch at Scale

Optimize Elasticsearch for millions of records with better pagination, leaner payloads, efficient filtering, faster ingestion, and frontend techniques that keep search responsive with increase in data.

Insight
Deep Linking for Mobile Apps(React Native) with NestJs, AWS CloudFront, S3 & ALB: A Complete Guide
Oct 13, 2026

Deep Linking for Mobile Apps(React Native) with NestJs, AWS CloudFront, S3 & ALB: A Complete Guide

Build a self-hosted deep linking and referral system for React Native without a third-party SDK. This guide covers Android App Links, iOS Universal Links, an S3 and CloudFront setup, and a NestJS backend that routes users to the right app store.

Insight
How We Engineered a Three-Path Reward Processing System for a Real-Time Sports Platform
Oct 12, 2026

How We Engineered a Three-Path Reward Processing System for a Real-Time Sports Platform

This blog explains how a real-time sports platform uses synchronous, asynchronous, and scheduled processing paths to handle rewards without slowing down the player experience.

Insight
Building an MCP-Powered QA Agent
Oct 12, 2026

Building an MCP-Powered QA Agent

Build an MCP QA agent that runs Playwright tests, validates APIs, and analyzes failures through a controlled, auditable tool layer with human approval.

Insight
From Test Failure to Root Cause: Building an AI-Assisted Playwright Failure Analysis Pipeline
Oct 9, 2026

From Test Failure to Root Cause: Building an AI-Assisted Playwright Failure Analysis Pipeline

This blog explains how an AI-assisted Playwright pipeline can analyze test failure evidence, identify probable root causes, and support human-validated debugging.

Insight
The Model Context Protocol: From First Call to Production
Oct 8, 2026

The Model Context Protocol: From First Call to Production

This blog explains how Model Context Protocol (MCP) works, from tool discovery and execution to OAuth authorization, security controls, and production deployment.

Insight
Stop Automating Everything: A Balanced Quality Engineering Approach to Testing
Oct 8, 2026

Stop Automating Everything: A Balanced Quality Engineering Approach to Testing

Balanced quality engineering places automation, API testing, exploratory work, and AI where each gives the most value, so teams ship faster without trading away user-perceived quality.

Footer

The Right Conversation Can

Save You Six Months.

Book a Call