33 lines
808 B
TypeScript
33 lines
808 B
TypeScript
import { useEffect, useRef, useState } from "react";
|
|
|
|
/**
|
|
* 요소가 뷰포트에 진입하면 inView = true 로 바뀌는 훅.
|
|
* framer-motion의 whileInView({ once: true }) 와 동일한 동작.
|
|
*/
|
|
export function useInView<T extends HTMLElement = HTMLElement>(
|
|
options?: IntersectionObserverInit,
|
|
) {
|
|
const ref = useRef<T>(null);
|
|
const [inView, setInView] = useState(false);
|
|
|
|
useEffect(() => {
|
|
const el = ref.current;
|
|
if (!el) return;
|
|
|
|
const observer = new IntersectionObserver(
|
|
([entry]) => {
|
|
if (entry.isIntersecting) {
|
|
setInView(true);
|
|
observer.disconnect(); // once: true
|
|
}
|
|
},
|
|
{ threshold: 0.15, ...options },
|
|
);
|
|
|
|
observer.observe(el);
|
|
return () => observer.disconnect();
|
|
}, []);
|
|
|
|
return { ref, inView };
|
|
}
|