100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace

How Do You Implement Infinite Scroll?

Learn how to implement infinite scroll with IntersectionObserver, avoid duplicate fetches, and keep the DOM performant.

mediumQ158 of 224 in Web Development Est. time: 5 minsLast updated:
Open Code Lab

Expected Interview Answer

Infinite scroll loads additional pages of content automatically as the user nears the bottom of the current list, typically detected with an IntersectionObserver watching a sentinel element, rather than requiring an explicit next-page click.

The core mechanism places an invisible sentinel element near the end of the rendered list and observes it with an IntersectionObserver, which fires a callback once the sentinel scrolls into the viewport, signaling it is time to fetch the next page and append it to the existing list. This is more efficient than listening to scroll events directly and computing scroll position on every frame, since IntersectionObserver runs asynchronously off the main thread’s scroll handling. A production implementation must guard against firing multiple fetches for the same page (using an isLoading flag), handle the end of data (no more pages), and consider performance for very long lists via windowing or virtualization so the DOM does not accumulate thousands of nodes. It also needs an accessible fallback, like a manual load-more button, for users relying on keyboard navigation or those who prefer not to rely on automatic scroll triggers.

  • Removes friction of manual pagination clicks for continuously browsable content
  • IntersectionObserver is more performant than manual scroll-position calculations
  • Loads content just-in-time, avoiding fetching data the user may never scroll to
  • Pairs well with virtualization to keep DOM size bounded for very long lists

AI Mentor Explanation

Infinite scroll is like a scoreboard operator who prepares the next over’s details only once fans’ attention visibly reaches the current over’s last ball, rather than printing every over for the whole day upfront. A sentinel marker — the last visible ball — triggers preparation of the next batch just in time. If the operator is already fetching the next over, they will not start fetching it twice. That watch-the-edge, fetch-just-in-time, avoid-duplicate-fetch behavior is exactly how infinite scroll works with an IntersectionObserver.

Step-by-Step Explanation

  1. Step 1

    Render a sentinel element

    Place an empty div at the end of the currently rendered list, below the last item.

  2. Step 2

    Observe it with IntersectionObserver

    Attach an observer that fires a callback once the sentinel scrolls into (or near) the viewport.

  3. Step 3

    Fetch and append the next page

    On intersection, request the next page of data and append it to existing state, guarded by an isLoading flag.

  4. Step 4

    Handle the end of data and cleanup

    Stop observing once no more pages exist, and disconnect the observer when the component unmounts.

What Interviewer Expects

  • Correct use of IntersectionObserver rather than manual scroll-position math
  • Awareness of guarding against duplicate fetches while a request is in flight
  • Consideration of DOM growth and virtualization for very long lists
  • Accessibility awareness, such as offering a manual load-more fallback

Common Mistakes

  • Using scroll event listeners with manual position math instead of IntersectionObserver
  • Not guarding against firing multiple simultaneous fetches for the same page
  • Letting the DOM grow unbounded for very long lists without virtualization
  • Forgetting to disconnect the observer on unmount, causing memory leaks

Best Answer (HR Friendly)

Infinite scroll automatically loads more items as you scroll near the bottom of a list, so you never have to click a next-page button. Technically it works by watching an invisible marker near the end of the list with a browser API called IntersectionObserver, and fetching the next batch the moment that marker comes into view.

Code Example

Infinite scroll with IntersectionObserver
function useInfiniteScroll(fetchPage) {
  const [items, setItems] = React.useState([])
  const [page, setPage] = React.useState(1)
  const [hasMore, setHasMore] = React.useState(true)
  const [isLoading, setIsLoading] = React.useState(false)
  const sentinelRef = React.useRef(null)

  React.useEffect(() => {
    const observer = new IntersectionObserver(async (entries) => {
      const [entry] = entries
      if (entry.isIntersecting && hasMore && !isLoading) {
        setIsLoading(true)
        const nextItems = await fetchPage(page)
        setItems(prev => [...prev, ...nextItems])
        setHasMore(nextItems.length > 0)
        setPage(prev => prev + 1)
        setIsLoading(false)
      }
    }, { rootMargin: '200px' })

    if (sentinelRef.current) observer.observe(sentinelRef.current)
    return () => observer.disconnect()
  }, [page, hasMore, isLoading, fetchPage])

  return { items, sentinelRef, hasMore }
}

Follow-up Questions

  • How would you prevent the DOM from growing unbounded on a very long infinite-scroll list?
  • What accessibility fallback would you offer for infinite scroll?
  • How does rootMargin on IntersectionObserver affect when the next page loads?
  • How would you preserve scroll position when a user navigates back to an infinite-scroll list?

MCQ Practice

1. What is the modern, performant way to detect when a user has scrolled near the end of a list?

IntersectionObserver asynchronously detects visibility of a sentinel element without manual scroll-position math.

2. Why is a loading guard flag necessary in an infinite scroll implementation?

Without a guard, rapid re-triggering of the intersection callback could fire duplicate requests for the same page.

3. What technique helps keep the DOM size bounded for very long infinite-scroll lists?

Virtualization renders only the visible subset of items, keeping the DOM node count bounded regardless of total list length.

Flash Cards

What triggers the next page fetch in infinite scroll?A sentinel element becoming visible, detected via IntersectionObserver.

Why avoid scroll event listeners for this?IntersectionObserver is more performant and avoids manual scroll-position calculations.

What prevents duplicate fetches?An isLoading guard flag checked before triggering a new fetch.

How to handle very long lists?Pair infinite scroll with virtualization/windowing to bound DOM size.

1 / 4

Continue Learning