1. useFadeIn
opacity 0 에서 opacity 1로 만드는 hook
import "./styles.css";
import { useState, useEffect, useRef } from "react";
const useFadeIn = (duration = 1, delay = 0) => {
// 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 } };
};
function App() {
const fadeInH1 = useFadeIn(2, 1);
const fadeInP = useFadeIn(5, 2);
return (
<div className="App">
<h1 {...fadeInH1}>Hi</h1>
<p {...fadeInP}>lalalalalalalalalallalaalallll</p>
</div>
);
}
export default App;
useFadeIn 함수의 최종 리턴값은 opacity 0인데 왜 실행 화면에서는 opcity 0에서 1로 보여지게 되는 건지 이해가 안됐다.
질문해서 답을 얻은 결과!
useEffect는 componentDidMount때 실행되는 훅이다.
처음 마운트될 때 useFadeIn가 실행되고(opacity: 0) 그 이후에 useEffect(opacity: 1)가 실행된다.
그래서 opacity 0에서 1이 되는 것이다!! wowwwwwwwww!!
라이프사이클을 좀 더 잘 이해하게 된 계기가 되었다!!
2. useNetwork
네비게이션이 online offline 되는 것을 막아줌
import "./styles.css";
import { useState, useEffect, useRef } from "react";
const useNetwork = (onChange) => {
const [status, setStatus] = useState(navigator.onLine);
// ture or 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);
};
// mount 되지 않을 때 지워줌
}, []);
return status;
};
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>
);
}
export default App;
몰라 ...... 어렵다 내일 복습하기
'react' 카테고리의 다른 글
[react] Hooks란? (0) | 2022.12.14 |
---|---|
[react] 라이프사이클(mount, update, unmount) (0) | 2022.12.14 |
[react] usePreventLeave, useBeforeLeave (0) | 2022.12.13 |
[react] react-icons 사용하기 (0) | 2022.12.13 |
[react] npm sass 설치 오류, npm과 yarn 차이 (0) | 2022.12.13 |