Useful Javascript function

This is the javascript function that allow you to check if the internet connection is available or not. Simply call this function will return true or false.


import React, { useState, useEffect } from 'react';

const Online = () => {

    const [mode, setMode] = useState(navigator.onLine);

    useEffect(() => {
        window.addEventListener('online', handleNetwork);
        window.addEventListener('offline', handleNetwork);

        // componentDidMount() 
        // componentDidUpdate()
        // componentWillUnMount()
        return () => {
            window.removeEventListener('online', handleNetwork);
            window.removeEventListener('offline', handleNetwork);
    }, [mode]); // value inside array will execute everytime after effect

    const handleNetwork = (event) => {

    return (
            <h1>Online status</h1>
            <p> Mode: {mode ? "online" : "offline"} </p>

export default Online;

Useful Javascript function

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.