Skip to content

Commit

Permalink
feat: useIntersectionObserver 훅 구현
Browse files Browse the repository at this point in the history
  • Loading branch information
dlwl98 committed Oct 30, 2023
1 parent b40aa7c commit 0c57675
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/hooks/useIntersectionObserver.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { useEffect, useRef, useState } from 'react';

export const useIntersectionObserver = <T extends HTMLElement>({
threshold = 0,
root = null,
rootMargin = '0%',
}: IntersectionObserverInit) => {
const ref = useRef<T | null>(null);
const [entry, setEntry] = useState<IntersectionObserverEntry>();

useEffect(() => {
if (!ref.current) {
return;
}

const observer = new IntersectionObserver(
([entry]) => {
setEntry(entry);
},
{ threshold, root, rootMargin }
);

observer.observe(ref.current);

return () => observer.disconnect();
}, [ref, threshold, root, rootMargin]);

return [ref, entry] as const;
};

0 comments on commit 0c57675

Please sign in to comment.