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)