@jk-core/hooks
Version:
hooks for jk
34 lines (27 loc) • 964 B
text/typescript
import { useEffect } from 'react';
interface IntersectionObserverProps<T1 extends HTMLElement, T2 extends HTMLElement> {
target: React.RefObject<T1 | null>;
parent?: React.RefObject<T2 | null>;
callback: () => void;
options?: IntersectionObserverInit;
}
// 인피니티 스크롤 옵저버설정 훅
const useIntersectionObserver = <T1 extends HTMLElement, T2 extends HTMLElement>({
target, parent, callback, options,
}:IntersectionObserverProps<T1, T2>) => {
useEffect(() => {
const ref = target.current;
const parentRef = parent?.current;
if (!ref) return () => { };
const observer = new IntersectionObserver(([entry]) => {
if (entry.isIntersecting) callback();
}, {
...parentRef ? { root: parentRef } : {}, threshold: 1, ...options,
});
observer.observe(ref);
return () => {
observer.unobserve(ref);
};
}, [callback, options, parent, target]);
};
export default useIntersectionObserver;