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)