From 0c57675c7a4b89f7d17ba2bbb034f55a6dc6b71f Mon Sep 17 00:00:00 2001 From: dlwl98 Date: Mon, 30 Oct 2023 21:16:48 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20useIntersectionObserver=20=ED=9B=85=20?= =?UTF-8?q?=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/hooks/useIntersectionObserver.ts | 29 ++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 src/hooks/useIntersectionObserver.ts diff --git a/src/hooks/useIntersectionObserver.ts b/src/hooks/useIntersectionObserver.ts new file mode 100644 index 00000000..6bc08005 --- /dev/null +++ b/src/hooks/useIntersectionObserver.ts @@ -0,0 +1,29 @@ +import { useEffect, useRef, useState } from 'react'; + +export const useIntersectionObserver = ({ + threshold = 0, + root = null, + rootMargin = '0%', +}: IntersectionObserverInit) => { + const ref = useRef(null); + const [entry, setEntry] = useState(); + + 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; +};