Frontend/React Hook

[React-Hooks] React Hooks - useFadeIn & useNetwork

갈푸라떼 2022. 7. 13. 01:25

* useFadeIn

  • useFadeIn은 어떤 요소를 시간이 지남에 따라 서서히나게 하는 hooks 입니다.

* useFadeIn 예시코드

import { useEffect, useRef } from "react";

const useFadeIn = (duration = 1, delay = 0) => {
  const element = useRef();
  useEffect(() => {
    if (typeof duration === "number" || typeof delay === "number") {
      if (element.current) {
        const { current } = element;
        current.style.transition = `opacity ${duration}s ease-in-out ${delay}s`;
        current.style.opacity = 1;
      }
    }
  }, []);
  return { ref: element, style: { opacity: 0 } };
};

const App = () => {
  const fadeIn = useFadeIn();
  return <h1 {...fadeIn}>Hello</h1>;
};

export default App;
  • transition-duration : 트랜지션이 일어나는 지속 시간을 명시하는 속성
  • transition-delay : 속성이 변하는 시점과 트랜지션이 실제로 시작하는 사이에 기다리는 시간을 정의

 


* useNetwork

  • navigator가 online 또는 offline되는걸 막아준다.
  • navigator.onLine은 나의 웹사이트가 온라인인지 아닌지에 따라서 true또는 false를 반환한다.
import { useEffect, useState } from "react";

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

const App = () => {
  const handleNetworkChange = (online) =>
    console.log(online ? "online!!!" : "offline");
  const onLine = useNetwork(handleNetworkChange);
  return (
    <>
      <h1>{onLine ? "Online" : "offline"}</h1>
    </>
  );
};

export default App;
  • 네트워크가 online일 경우 offline일 경우에 맞게 true false가 반환되어 hook이 실행된다.