Sequence NODE_195
MediumImplement Infinite Scroll for a List
React
JavaScript
Technical Specification
Load more items when the user scrolls near the bottom of the list.
Input/Output Samples
Input:Scroll down
Output:More items auto-append
Optimal Logic Path
import { useState, useEffect, useRef } from "react";
const DATA = Array.from({ length: 100 }, (_, i) => "Item " + (i + 1));
function InfiniteList() {
const [count, setCount] = useState(20);
const loadMoreRef = useRef(null);
useEffect(() => {
const el = loadMoreRef.current;
if (!el) return;
const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
setCount((c) => Math.min(DATA.length, c + 10));
}
});
observer.observe(el);
return () => observer.disconnect();
}, []);
const visible = DATA.slice(0, count);
return (
<div>
<ul>
{visible.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
<div ref={loadMoreRef}>Loading more...</div>
</div>
);
}Architectural Deep-Dive
We observe a sentinel element at the bottom and increase count when it becomes visible.