본문 바로가기

Java Scripts/React.js

Hook in React - useNetwork

728x90

note) network 이 online 인지 offline 인지 인지하여 화면에 표시해 준다.

 

note) 동작을 확인하기 위하여는 chrome broser 에서 inspect -> Network 에서 Fast 3G 를 누르면 Browser 를 offline 으로 만들수 있고, offline 이 되면 화면도 같이 offline 으로 표시된다.

 

note)  offline online event handler 를 useEffect 안에서 self 로 등록 해제가 되고 있는 멋진 code 이다.

 

note) sample working codes

import { useState, useEffect } from "react";

export const useNetwork = (onChange) => {
  const [status, setStatus] = useState(navigator.onLine || true);
  const handleChange = () => {
    if (onChange && typeof onChange === "function") {
      onChange(navigator.onLine);
    }
    setStatus(navigator.onLine);
  };
  useEffect(() => {
    window.addEventListener("online", handleChange);
    window.addEventListener("offline", handleChange);
    () => {
      window.removeEventListener("online", handleChange);
      window.removeEventListener("offline", handleChange);
    };
  }, []);
  return status;
};

export default function App() {
  const handleNetworkChange = (online) => {
    console.log(online ? "We just went online" : "We are offline");
  };
  const online = useNetwork(handleNetworkChange);
  return (
    <div className="App">
      <h1>{online ? "Online" : "Offline"}</h1>
    </div>
  );
}

note) 위는 아래의 교육과장을 이수하면서 정리한 것이다.

https://nomadcoders.co/react-hooks-introduction/lobby?utm_source=free_course&utm_campaign=react-hooks-introduction&utm_medium=site

'Java Scripts > React.js' 카테고리의 다른 글

Hook in React - useNotification  (0) 2023.10.07
Hook in React - useScroll  (0) 2023.10.07
Hook in React - useBeforeLeave  (0) 2023.10.07
Hook in React - usePreventLeave  (0) 2023.10.07
Hook in React - useAxios  (0) 2023.09.28