해당요소가 완전히 다 보일 때 true 반환하는 Hook 만들기

1 minute read
2024-08-17

코드

import { useInView } from "framer-motion";
 
function useIsFullyVisible() {
  const ref = useRef(null);
  const isFullyVisible = useInView(ref, { amount: 1 });
 
  return { ref, isFullyVisible };
}


여기서 amount요소가 100% 다 화면에 보일 때를 기준으로 한다.


적용하는 곳에서는


Footer.tsx
const Footer = () => {
  const [_, setIsInPriceView] = useIsInPriceView()
  const { ref, isFullyVisible } = useIsFullyVisible()
 
  useEffect(() => {
    if (isFullyVisible) {
      setIsInPriceView(true)
    } else {
      setIsInPriceView(false)
    }
  }, [isFullyVisible, setIsInPriceView])
 
  return (
    <footer
      ref={ref}
			// ...
		></footer>
	)
}


위 예제 코드의 이름에서 atom 이름이 좀 아쉽긴 하다.