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
Why Legacy Systems Make Business Growth More Expensive: Navigate A Smarter Path to Legacy Modernization
Sep 23, 2026

Why Legacy Systems Make Business Growth More Expensive: Navigate A Smarter Path to Legacy Modernization

Learn how legacy systems make business growth more expensive and how edge-first modernization can remove constraints without replacing the existing system.

Insight
SSO, Audit Logs and RBAC: The Enterprise Features AI Prototyping Tools Do Not Cover | Sarika Gautam
Sep 23, 2026

SSO, Audit Logs and RBAC: The Enterprise Features AI Prototyping Tools Do Not Cover | Sarika Gautam

Why AI-generated prototypes fail enterprise review: the context behind SSO, the cost of skipping audit logs, and how role explosion makes RBAC a product of its own.

Insight
Feature Flags as Technical Debt: The Cleanup Nobody Schedules
Sep 21, 2026

Feature Flags as Technical Debt: The Cleanup Nobody Schedules

This blog explains how unmanaged feature flags create technical debt and how teams can detect, manage, and remove them safely.

Insight
Building AI-First Enterprises: Why System Design Matters More Than AI Adoption
Sep 21, 2026

Building AI-First Enterprises: Why System Design Matters More Than AI Adoption

This blog explores how system design, architecture, and validation shape AI-first enterprises, while examining AI’s impact on software engineering and human decision-making.

Insight
The Product Studio in the AI Era: What Actually Changes | Sarika Gautam
Sep 21, 2026

The Product Studio in the AI Era: What Actually Changes | Sarika Gautam

What changes in product development when AI writes the code: the shift to architecture, the token cost of unplanned builds, and why juniors still matter.

Insight
AI and the Future of Digital Customer Experience: Where Technology Meets Human Creativity
Sep 18, 2026

AI and the Future of Digital Customer Experience: Where Technology Meets Human Creativity

A discussion on how AI, human creativity, research, and cross-functional collaboration are shaping the future of digital customer experience.

Insight
Scaling Down Before Scaling Up: Why Bigger Servers Don’t Fix Bad Architecture
Sep 17, 2026

Scaling Down Before Scaling Up: Why Bigger Servers Don’t Fix Bad Architecture

This blog explores how inefficient backend architecture can cause performance issues even under low traffic, covering practical ways to reduce database load, API latency, and resource usage before scaling infrastructure.

The Right Conversation Can

Save You Six Months.

Book a call