DEV Community

Cover image for React Custom Hooks (useNetworkStatus)
sundarbadagala
sundarbadagala

Posted on

React Custom Hooks (useNetworkStatus)

INTRO 🔊

Hello World! 👋
Today we are discussing another custom hook named useNetworkStatus🔥. In this post, we will discuss this hook's usage, code and use case.

USAGE 🔊

Sometimes developers want to know whether the user is offline or online. By using JavaSCript we can find the user status (offline/online). But creating a custom hook and using it whenever we want is better than using JavaScript code every time right? For that purpose, we are creating one custom today.

CODE 🔊

import {useState,useEffect} from 'react'

 const useNetworkStatus=()=> {

    const [isOnline, setIsOnline] = useState(navigator.onLine);

    useEffect(() => {
      window.addEventListener('online', () => {
        setIsOnline(navigator.onLine);
      });
      window.addEventListener('offline', () => {
        setIsOnline(navigator.onLine);
      });

      return ()=>{
        window.removeEventListener("online", setIsOnline);
        window.removeEventListener("offline", setIsOnline);
      }
    });

    return isOnline;
  }

  export default useNetworkStatus
Enter fullscreen mode Exit fullscreen mode

USE CASE 🔊

import React from 'react';
import { useNetworkStatus } from 'share/hooks';

function Index() {
  const isOnlie = useNetworkStatus();
  return <div>Index</div>;
}

export default Index;
Enter fullscreen mode Exit fullscreen mode

CONCLUSION 🔊

By using the above hook, we can find whether is online or not.

I hope you people like the useNetworkStatus hook. We will meet with another hook in another post.

Peace 🙂

Top comments (0)