Skip to content

Instantly share code, notes, and snippets.

@jinsley8
Created November 29, 2022 22:20
Show Gist options
  • Save jinsley8/72f0b67cbb6a435a5a1bae576eabbc5d to your computer and use it in GitHub Desktop.
Save jinsley8/72f0b67cbb6a435a5a1bae576eabbc5d to your computer and use it in GitHub Desktop.
A hook to observe when the uses has scrolled to on page
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