const useNetwork = onChange => {
const [status, setStatus] = useState(navigator.onLine); // true 또는 false 값
const handleChange = () => {
if (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;
};
const App = () => {
const onNetworkChange = isOnline => {
console.log(isOnline ? "We are back online" : "We just got offline");
};
const online = useNetwork(onNetworkChange);
return (
<div className="App">
<h1>{isOnline ? "We are online" : "We are offline"} </h1>
<p>Welcome</p>
</div>
);
};