Skip to content

Commit

Permalink
✨ Feat: Intersection Observer 사용을 위한 커스텀 훅 분리
Browse files Browse the repository at this point in the history
  • Loading branch information
sy-paik committed Nov 25, 2023
1 parent 1192c1b commit cbecf03
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions src/hook/useObserver.js
Original file line number Diff line number Diff line change
@@ -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;
}

0 comments on commit cbecf03

Please sign in to comment.