AdSense Leaderboard

Google AdSense Placeholder

HEADER SLOT

Custom useInfiniteScroll Hook

Last updated:

Implement infinite scrolling efficiently using the Intersection Observer API (no scroll event listeners).

The Code

This hook returns a ref. Assign this ref to the last element in your list. When that element becomes visible, the callback fires.

typescript
import { useRef, useCallback } from 'react';

export function useInfiniteScroll(
  isLoading: boolean,
  hasMore: boolean,
  callback: () => void
) {
  const observer = useRef<IntersectionObserver>();

  const lastElementRef = useCallback(
    (node: HTMLElement | null) => {
      if (isLoading) return;
      
      if (observer.current) observer.current.disconnect();
      
      observer.current = new IntersectionObserver((entries) => {
        if (entries[0].isIntersecting && hasMore) {
          callback();
        }
      });

      if (node) observer.current.observe(node);
    },
    [isLoading, hasMore, callback]
  );

  return lastElementRef;
}
Sponsored Content

Google AdSense Placeholder

CONTENT SLOT

Sponsored

Google AdSense Placeholder

FOOTER SLOT