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
USE CASE π
import React from 'react';
import { useNetworkStatus } from 'share/hooks';
function Index() {
const isOnlie = useNetworkStatus();
return <div>Index</div>;
}
export default Index;
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)