Unveiling Connectivity: Introducing useNetworkStatus

Welcome to the third installment of our "Custom Hooks Deep Dive" series! In this edition, we shine a spotlight on the versatile useNetworkStatus custom hook, designed to effortlessly monitor and manage the online/offline status of your React applications.

The Core of useNetworkStatus

// useNetworkStatus.js
import { useState, useEffect } from "react";

const useNetworkStatus = () => {
  const [status, setStatus] = useState(navigator.onLine);

  useEffect(() => {
    const setOnline = () => {
      setStatus(true);
    };

    const setOffline = () => {
      setStatus(false);
    };

    window.addEventListener("online", setOnline);
    window.addEventListener("offline", setOffline);

    return () => {
      window.removeEventListener("online", setOnline);
      window.removeEventListener("offline", setOffline);
    };
  }, []);

  return status;
};

export default useNetworkStatus;

How It Works

The useNetworkStatus hook leverages useState and useEffect to manage the online/offline status of your application. It initializes the status state with the current online status obtained from navigator.onLine.

The useEffect hook sets up event listeners for the "online" and "offline" events, updating the status state accordingly. The cleanup function ensures the removal of these event listeners when the component unmounts.

Real-world Application

Imagine you're building a web application that relies on real-time updates or data synchronization. With useNetworkStatus, you can seamlessly adapt your UI to different connectivity scenarios. Display a notification when the user goes offline or trigger a synchronization process when the connection is restored.

import React from 'react';
import useNetworkStatus from './useNetworkStatus';

const RealTimeApp = () => {
  const isOnline = useNetworkStatus();

  return (
    <div className="real-time-app">
      <h1>Real-Time Application</h1>
      <p>Status: {isOnline ? 'Online' : 'Offline'}</p>
      {/* Your real-time features and logic go here */}
    </div>
  );
}

export default RealTimeApp;

Conclusion

In this installment, we've explored the useNetworkStatus custom hook, a powerful tool for monitoring online/offline status in your React applications. Stay tuned for more insights, practical applications, and innovative custom hooks as we continue our deep dive. Happy coding!