hook isOnline React

Viewed 29

I have an app and I would like to know if there is a way to improve my hook below. I am trying to avoid making a request and I do not wish to use the navigator.OnLine.

Here is what I have but I am in search of a solution.

 export const useOnline = () => {
  const [status, setStatus] = useState(navigator.onLine || true);

  const handleChange = () => {
    setStatus(navigator.onLine);
  };

  useEffect(() => {
    window.addEventListener("online", handleChange);
    window.addEventListener("offline", handleChange);
    () => {
      window.removeEventListener("online", handleChange);
      window.removeEventListener("offline", handleChange);
    };
  }, []);

  return status;
};

0 Answers
Related