Apr 22, 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

Subject Matter Expert


Book a call
Table of Contents
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.
Breakdown of the Code
Let us dissect the individual parts of the useNetworkState hook:
- State Definition:
- The hook starts by defining a type alias named
NetworkStateto 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
useStatehook is used to create a state variable namednetworkStatewith the initial value set based on the currentnavigator.onLineproperty. This ensures the hook reflects the initial network state upon first render.
- The hook starts by defining a type alias named
updateNetworkStateFunction:- This function, declared using
useCallback, is responsible for updating thenetworkStatebased on the current online status. It performs the following actions:- Attempts to update the
onlineproperty of the state with the currentnavigator.onLinevalue. - If any error occurs during the update, it logs the error message and sets the
errorproperty of the state with a generic error message.
- Attempts to update the
- This function, declared using
useEffectHook:- 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
windowobject, triggering theupdateNetworkStatefunction whenever the network status changes. - Calls the
updateNetworkStatefunction immediately after theuseEffecthook 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.
- Adds event listeners for both "online" and "offline" events to the
- This hook manages the lifecycle of event listeners and state updates related to network changes. It performs the following actions:
- Returning the State:
- The hook simply returns the current value of the
networkStateobject, allowing components that use this hook to access theonlineanderrorproperties for further processing and UI updates.
- The hook simply returns the current value of the
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.
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.
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.

Apr 23, 2026
From Manual Testing to AI-Assisted Automation with Playwright Agents
This blog discusses the value of Playwright Agents in automating workflows. It provides a detailed description of setting up the system, as well as a breakdown of the Playwright Agent’s automation process.

Apr 14, 2026
The Keyboard Bounce of Death: Handling Inputs on Complex React Native Screens
Fix the React Native ‘Keyboard Bounce of Death.’ Learn why inputs jump and how to build smooth, production-ready forms with modern architecture.

Apr 9, 2026
From RFPs to Revenue: How We Built an AI Agent Team That Writes Technical Proposals in 60 Seconds
GeekyAnts built DealRoom.ai — four AI agents that turn RFPs into accurate technical proposals in 60 seconds, with real-time cost breakdowns and scope maps.

Apr 6, 2026
How We Built an AI System That Automates Senior Solution Architect Workflows
Discover how we built a 4-agent AI co-pilot that converts complex RFPs into draft technical proposals in 15 minutes — with built-in conflict detection, assumption surfacing, and confidence scoring.

Apr 6, 2026
AI Code Healer for Fixing Broken CI/CD Builds Fast
A deep dive into how GeekyAnts built an AI-powered Code Healer that analyzes CI/CD failures, summarizes logs, and generates code-level fixes to keep development moving.

Apr 2, 2026
A Real-Time AI Fraud Decision Engine Under 50ms
A deep dive into how GeekyAnts built a real-time AI fraud detection system that evaluates transactions in milliseconds using a hybrid multi-agent approach.

