본문 바로가기
WEB/Front-End🌝

[React Hooks] useFadeln, useNetwork, useScroll

by narang111 2021. 12. 19.

useFadeIn

import "./styles.css";
import React, { useState, useEffect, useRef } from "react";

const useFadeIn = (duration = 1, delay = 0) => {
  if (typeof duration !== "number" || typeof delay !== "number") {
    return;
  }
  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 } };
};

export default function App() {
  const fadeInH1 = useFadeIn(1, 2);
  const fadeInP = useFadeIn(5, 5);
  return (
    <div className="App">
      <h1 {...fadeInH1}>Hello</h1>
      <p {...fadeInP}>nice to meet you</p>
    </div>
  );
}

 

 

useNetwork

import "./styles.css";
import React, { useState, useEffect, useRef } 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);
    ()=>{
      window.removeEventListener("online", handleChange);
      window.removeEventListener("offline", handleChange);
    }
  }, []);
  return status;
}

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

 

 

useScroll

- 마우스의 스크롤을 감지해서 위로 갈 때는 파랑, 아래는 빨간색으로 바뀐다.

import "./styles.css";
import React, { useState, useEffect, useRef } from "react";

const useScroll = () => {
  const [state, setState] = useState({
    x: 0,
    y: 0
  });
  const onScroll = (event) => {
    setState({y: window.scrollY, x: window.scrollX});
  };
  useEffect(() => {
    window.addEventListener("scroll", onScroll);
    return () => {
      window.removeEventListener("scroll", onScroll);
    };
  }, []);
  return state;
};

export default function App() {
  const { y } = useScroll();
  return (
    <div className="App" style={{ height: "1000vh" }}>
      <h1 style={{ position: "fixed", color: y > 100 ? "red" : "blue" }}>Hi</h1>
    </div>
  );
}