From cbecf03d9d2325625cab3f8a8ea28117cc652da4 Mon Sep 17 00:00:00 2001 From: soo yeon <80268199+sypaik-dev@users.noreply.github.com> Date: Sat, 25 Nov 2023 21:40:19 +0900 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20Feat:=20Intersection=20Observer=20?= =?UTF-8?q?=EC=82=AC=EC=9A=A9=EC=9D=84=20=EC=9C=84=ED=95=9C=20=EC=BB=A4?= =?UTF-8?q?=EC=8A=A4=ED=85=80=20=ED=9B=85=20=EB=B6=84=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/hook/useObserver.js | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 src/hook/useObserver.js diff --git a/src/hook/useObserver.js b/src/hook/useObserver.js new file mode 100644 index 0000000..4bb9e07 --- /dev/null +++ b/src/hook/useObserver.js @@ -0,0 +1,28 @@ +import React, { useCallback, useEffect, useRef } from 'react'; + +export default function useObserver(hasNextPage, fetchNextPage, isLoading) { + const observerRef = useRef(); + + const handleIntersection = useCallback( + (entries) => { + const [target] = entries; + if (target.isIntersecting && hasNextPage) { + fetchNextPage(); + } + }, + [fetchNextPage, hasNextPage], + ); + + useEffect(() => { + const element = observerRef.current; + if (!element) return + const options = { threshold: 0 }; + const observer = new IntersectionObserver(handleIntersection, options); + if (element) { + observer.observe(element); + return () => observer.disconnect(); + } + }, [fetchNextPage, handleIntersection, isLoading]); + + return observerRef; +}