My Develop Log

[노마드코더]실전형 리액트 Hooks 10개 - (useFadeIn & useNetwork) 본문

React 공부/노마드코더 노트정리

[노마드코더]실전형 리액트 Hooks 10개 - (useFadeIn & useNetwork)

Developer_Sammy 2023. 2. 8. 21:59
useFadeIn

useFadeIn은 서서히 나타나는 애니메이션 효과를 주는 hook이다.

  • 우선,  useRef를 사용해 element에 접근하여 transition의 opacity의 지연 시간을 5초로 설정
// app.js

import { useEffect, useRef } from "react";

const usefadeIn = () => {
  // useRef를 사용해 element에 접근
  const element = useRef();
  useEffect(() => {
    if (element.current) {
      const { current } = element;
      current.style.transition = `opacity 5s`;
      current.style.opacity = 1;
    }
  }, []);
  return { ref: element, style: { opacity: 0 } };
};

const App = () => {
  const fadeInH1 = usefadeIn();
  return (
    <div className="App">
      <h1 {...fadeInH1}> Hello </h1>
    </div>
  );
};

export default App;

 

  • 다음으로는 opacity 스타일에 duration과 ease-in-out 스타일에 delay 옵션을 추가했다. default로 duration은 1, delay는 0으로 설정
// app.js

import { useEffect, useRef } from "react";

const usefadeIn = (duration = 1, delay = 0) => {
  if (typeof duration !== "number" || typeof delay !== "number") {
    return;
  }
  // useRef를 사용해 element에 접근
  const element = useRef();
  useEffect(() => {
    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 fadeInH1 = usefadeIn(1, 2); // 1초 후, 2초에 걸쳐 서서히 보임
  const fadeInP = usefadeIn(3, 3); // 3초 후, 3초에 걸쳐 서서히 보임
  return (
    <div className="App">
      <h1 {...fadeInH1}> Hello </h1>
      <p {...fadeInP}>Welcome</p>
    </div>
  );
};

export default App;


useNetwork

useNetwork는 navigation 객체의 onLine 속성을 통해 online 혹은 offline의 상태를 알려줄 수 있도록 구현한 훅이다. 이는 인터넷이 중간에 끊겼다면 "사용자에게 인터넷이 끊겼습니다"라고 알려줄 수 있게 응용 가능하다.

  • network의 상태가 바뀔 때, h1으로 현재 online인지 띄워주고, handelNetworkChange 함수를 통해 console 창으로 알려준다.
// app.js

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); //online 상태이면 true, offline 상태이면 false
  };
  useEffect(() => {
    window.addEventListener("online", handleChange);
    window.addEventListener("offline", handleChange);

    // cleanup 함수
    () => {
      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 (
    <div className="APP">
      <h1>{onLine ? "Online" : "Offline"}</h1>
    </div>
  );
};

export default App;


Reference

https://nomadcoders.co/react-hooks-introduction/lectures/1598

 

All Courses – 노마드 코더 Nomad Coders

초급부터 고급까지! 니꼬쌤과 함께 풀스택으로 성장하세요!

nomadcoders.co