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.

Author

Daya
DayaSoftware Engineer III

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
Building Production-Grade Video Thumbnail Scrubbing in the Browser: HLS, Frame Extraction, Caching, and Performance Trade-offs
Sep 7, 2026

Building Production-Grade Video Thumbnail Scrubbing in the Browser: HLS, Frame Extraction, Caching, and Performance Trade-offs

This blog explains how to build responsive video thumbnail scrubbing in the browser for local files and HLS streams, covering frame extraction, caching, and performance trade-offs.

Insight
The Agent Can See Your App. How Often Can It Look?
Sep 4, 2026

The Agent Can See Your App. How Often Can It Look?

AI coding agents can now interact with mobile apps, but their effectiveness depends on iteration speed. This blog explores how React Native architecture influences feedback loops and AI-driven developer productivity.

Insight
Building Interactive Cards from Design JSON Without Killing Your Feed: Overlays, Video, Mute/Unmute, and Lag-Free Lists
Sep 1, 2026

Building Interactive Cards from Design JSON Without Killing Your Feed: Overlays, Video, Mute/Unmute, and Lag-Free Lists

Learn how to turn design JSON into interactive, video-enabled cards using overlays, smart media controls, caching, and virtualization without slowing down high-cardinality feeds.

Insight
The Bug That Doesn't Show Up in Code Review: Why Your Flutter Web App Reloads on Safari
Aug 19, 2026

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.

Insight
From Prompting to Process: What Changed When Flutter Shipped Agent Skills
Aug 19, 2026

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.

Insight
Why Everything Your AI Builds Looks the Same
Aug 19, 2026

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

Technology
How We Built the Missing Bridge from Code to Figma
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.

The Right Conversation Can

Save You Six Months.

Book a call