Created
November 29, 2022 22:20
-
-
Save jinsley8/72f0b67cbb6a435a5a1bae576eabbc5d to your computer and use it in GitHub Desktop.
A hook to observe when the uses has scrolled to on page
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useEffect } from 'react'; | |
interface IntersectionObserverProps { | |
root?: React.RefObject<Element | null>; | |
target: React.MutableRefObject<HTMLElement | null>; | |
onIntersect: () => void; | |
threshold?: number | number[]; | |
rootMargin?: string; | |
enabled?: boolean; | |
} | |
export default function useIntersectionObserver({ | |
root, | |
target, // loadMoreRef | |
onIntersect, // fetchNextPage | |
threshold = 1, // set as 1 or 0 | |
rootMargin = '0px', | |
enabled = true, // hasNextPage | |
}: IntersectionObserverProps): void { | |
useEffect(() => { | |
if (!enabled) { | |
return; | |
} | |
const observer = new IntersectionObserver( | |
(entries) => entries.forEach((entry) => entry.isIntersecting && onIntersect()), | |
{ | |
root: root && root.current, | |
rootMargin, | |
threshold, | |
} | |
); | |
const el = target && target.current; | |
if (!el) { | |
return; | |
} | |
observer.observe(el); | |
return () => { | |
observer.unobserve(el); | |
}; | |
}, [target.current, enabled]); // eslint-disable-line react-hooks/exhaustive-deps | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment