Skip to content

QuizNot attempted

Spot the bug: scroll listener plus IntersectionObserver

Both a scroll listener and an IntersectionObserver call loadMoreData. What is the best fix?
const handleScroll = () => {
if (lastElementRef.current &&
lastElementRef.current.getBoundingClientRect().bottom <= window.innerHeight) {
loadMoreData();
}
};
const observer = new IntersectionObserver(([entry]) => {
if (entry.isIntersecting) loadMoreData();
}, { threshold: 0.1 });
observer.observe(lastElementRef.current);
window.addEventListener('scroll', handleScroll);
1–4 to choose, Enter to submit
Show answer & explanation

Correct answer:

  • Keep only the IntersectionObserver on a sentinel row, and make "load more" a no-op unless idle with rows left
  • The observer already reports when the sentinel enters view, asynchronously and without layout reads.
  • Two triggers can both call loadMoreData before the re-render that sets isFetching, and both closures still see false, so two loads start.
  • Put the guard where it sees current state (a reducer that ignores loadMore unless idle, or a ref).
  • Not the scroll listener: it reads layout on every scroll event, and if the first page doesn't fill the screen nothing scrolls, so it never loads.
  • Not debounce: it adds latency and hides the race instead of removing it.
  • Not the isFetching check: it reads state captured in each closure, which doesn't change until React re-renders.