Frontend Blocks typescript Intermediate

Infinite Scroll via IntersectionObserver

Load more content as the user reaches the bottom — no scroll listeners, no jank.

typescript
import { useCallback, useRef } from 'react';
export function useInfiniteScroll(onLoadMore, hasMore) {
  const observer = useRef(null);
  return useCallback((node) => {
    observer.current && observer.current.disconnect();
    if (!node || !hasMore) return;
    observer.current = new IntersectionObserver(
      ([entry]) => { if (entry.isIntersecting) onLoadMore(); },
      { rootMargin: '200px' }
    );
    observer.current.observe(node);
  }, [onLoadMore, hasMore]);
}

Prerequisites

  • React >= 17

Pro Tips

  • → Pass rootMargin to start fetching before user hits bottom.

Was this module useful?

Share your experience — it helps the team improve.

Leave Feedback

Commercial Licensing

Acquire a production access token or template license for enterprise deployment.

Module Info

Language
typescript
Level
Intermediate
Read time
4 min
Published
Sep 2024
License
Commercial License

Newsletter

New modules every week, directly to your inbox.