Skip to content

Instantly share code, notes, and snippets.

@simenbrekken-visma
Last active February 24, 2022 12:59
Show Gist options
  • Save simenbrekken-visma/11d619f0707f6ee2ab4b8ca6163c861c to your computer and use it in GitHub Desktop.
Save simenbrekken-visma/11d619f0707f6ee2ab4b8ca6163c861c to your computer and use it in GitHub Desktop.
function Table() {
  // Dummy example
  const [page, setPage] = useState(0);
  const pages = 5;
  const hasMore = page < pages;
  
  function loadMore() {
    setPage(previousPage => previousPage + 1);
  }
  
  const loadMoreRef = useLoadMoreTarget(loadMore);
  
  return (
    <>
      <AllMyTableRows />
      {hasMore && <div ref={loadMoreRef} />}
    </>
  )
}
import { useEffect, useRef } from 'react';
export function useLoadMoreTarget<T extends HTMLElement>(
loadMore: () => void,
{ root, rootMargin, threshold }: IntersectionObserverInit = {}
): React.MutableRefObject<T | null> {
const targetRef = useRef<T | null>(null);
const loadMoreRef = useRef(loadMore);
useEffect(() => {
loadMoreRef.current = loadMore;
}, [loadMore]);
useEffect(() => {
const target = targetRef.current;
const loadMore = loadMoreRef.current;
if (target === null) {
return;
}
function onIntersection(entries: IntersectionObserverEntry[]) {
if (entries[0].isIntersecting) {
loadMore();
}
}
const observer = new IntersectionObserver(onIntersection, {
root,
rootMargin,
threshold,
});
observer.observe(target);
return () => {
observer.unobserve(target);
};
}, [root, rootMargin, threshold]);
return targetRef;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment