React: Check has internet connection

Posted on December 5, 2022
Tags: react

The following React code can be used to determine whether the user has an internet connection or not.

import { useEffect, useState } from "react";

const useHasInternet = () => {
  const [isOnline, setOnline] = useState(true);

  useEffect(() => {
    setOnline(navigator.onLine);

    const setIsOnline = () => {
      setOnline(true);
    };
    const setIsOffline = () => {
      setOnline(false);
    };

    window.addEventListener("online", setIsOnline);
    window.addEventListener("offline", setIsOffline);

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

  return { isOnline };
};

export default useHasInternet;