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.

ReactTechnologyreact hooks

Author

DayaDayaSoftware Engineer III

Subject Matter Expert

Tarun Bhagchand SoniTarun Bhagchand SoniSenior Software Engineer - II
Understanding and Implementing the Custom React Hook for Network State Monitoring
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

RELATED ARTICLES

More from the engineering frontline.

Dive deep into our research and insights on design, development, and the impact of various trends to businesses.
Why Legacy Systems Block Real-Time AI Decision-Making
Business

Aug 4, 2026

Why Legacy Systems Block Real-Time AI Decision-Making
Learn how legacy systems limit real-time AI decision-making and what businesses can do to build an AI-ready infrastructure.
What Makes an AI Product Enterprise-Ready? A Business Leader’s Perspective
Business

Aug 4, 2026

What Makes an AI Product Enterprise-Ready? A Business Leader’s Perspective
Most AI pilots never make it to production. Here are the five questions business leaders should ask before approving, buying, or scaling an AI product.
Building AI-Powered Banking CRM Platforms Without Replacing Core Banking Systems
Business

Jul 31, 2026

Building AI-Powered Banking CRM Platforms Without Replacing Core Banking Systems
Banks can modernize CRM with AI without replacing their core banking systems. This guide covers the architecture, use cases, governance, and roadmap to do it.
AI in Fintech: Everyone's Talking, Few are Shipping
Business

Jul 30, 2026

AI in Fintech: Everyone's Talking, Few are Shipping
This blog covers the key engineering, governance, and compliance principles required to build production-ready AI systems for financial services.
ERP and MES Integration for U.S. Pharma Manufacturers: A Roadmap to Achieve Zero-Error Production and End-to-End Traceability
Business

Jul 27, 2026

ERP and MES Integration for U.S. Pharma Manufacturers: A Roadmap to Achieve Zero-Error Production and End-to-End Traceability
A strategic roadmap for U.S. pharma leaders integrating ERP and MES to reduce production errors, accelerate batch release, strengthen compliance readiness, and enable end-to-end traceability across manufacturing sites.
How to Build Medical Device Software with AI: Compliance, Architecture, and Development Process
Business

Jul 24, 2026

How to Build Medical Device Software with AI: Compliance, Architecture, and Development Process
A guide for engineering leaders on building compliant, production-ready AI medical device software, from architecture to FDA clearance.

The Right Conversation Can Save You Six Months.

Whether you’re navigating AI adoption, modernizing legacy systems, or scaling a product - we start by listening. No pitch deck. No template. A real conversation.