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.

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.
The Bug That Doesn't Show Up in Code Review: Why Your Flutter Web App Reloads on Safari
The Bug That Doesn't Show Up in Code Review: Why Your Flutter Web App Reloads on Safari
A real-world look at how oversized images can trigger Safari reloads and iOS crashes in Flutter apps and how smarter image decoding prevents them.
From Prompting to Process: What Changed When Flutter Shipped Agent Skills
From Prompting to Process: What Changed When Flutter Shipped Agent Skills
This blog explores how Flutter Agent Skills improve AI-assisted development by combining official framework workflows with project-specific guidance for more consistent development.
Why Everything Your AI Builds Looks the Same
Why Everything Your AI Builds Looks the Same
This blog explores why AI-generated interfaces often look alike and explains how design systems, product context, and reusable engineering practices help teams build distinctive, scalable
How We Built the Missing Bridge from Code to Figma
Technology

Jul 10, 2026

How We Built the Missing Bridge from Code to Figma
This blog explores how AI-generated React apps get turned into fully editable, designer-ready Figma files by reading React Fiber instead of the DOM.
Building a Resilient Hybrid-Cloud Network with WireGuard HA, Route-Based Failover, and Deep Observability
Technology

Jun 27, 2026

Building a Resilient Hybrid-Cloud Network with WireGuard HA, Route-Based Failover, and Deep Observability
A practical breakdown of building resilient AWS-to-on-premises connectivity with WireGuard HA, active-standby failover, and deep packet-forwarding observability.
We Built a 114-Second AWS-to-Azure Failover. Here’s What We Learned
Technology

Jun 19, 2026

We Built a 114-Second AWS-to-Azure Failover. Here’s What We Learned
A practical guide to building a 114-second multi-cloud disaster recovery failover between AWS and Azure — what we built, what broke, and what we learned.
Cloud-Native and Cloud-Agnostic Are Not Ideologies; They Are Business-Stage Decisions
Technology

Jun 12, 2026

Cloud-Native and Cloud-Agnostic Are Not Ideologies; They Are Business-Stage Decisions
This blog explains how organizations can balance speed, scalability, and operational flexibility as they grow from startup to enterprise scale.

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.