May 5, 2025
Technology, Web Development
Infinite Scrolling, IntersectionObserver, React

Infinite scrolling is a popular technique used in modern web applications to enhance user experience by loading content continuously as the user scrolls. Instead of paginating data manually, infinite scroll loads new content automatically, reducing the need for navigation and making browsing smoother.
In this article, we’ll walk through how to implement infinite scrolling in a React application using a simple API and the IntersectionObserver API.
If you don’t already have a React project, create one:
npx create-react-app react-infinite-scroll
cd react-infinite-scroll
npm start
We’ll use JSONPlaceholder for mock data.
InfiniteScroll.js
import React, { useEffect, useRef, useState, useCallback } from 'react';
const InfiniteScroll = () => {
const [posts, setPosts] = useState([]);
const [page, setPage] = useState(1);
const [hasMore, setHasMore] = useState(true);
const loader = useRef(null);
const fetchPosts = useCallback(async () => {
const res = await fetch(`https://jsonplaceholder.typicode.com/posts?_limit=10&_page=${page}`);
const data = await res.json();
setPosts(prev => [...prev, ...data]);
if (data.length === 0 || data.length < 10) {
setHasMore(false);
}
}, [page]);
useEffect(() => {
fetchPosts();
}, [fetchPosts]);
useEffect(() => {
if (!hasMore) return;
const observer = new IntersectionObserver(entries => {
if (entries[0].isIntersecting) {
setPage(prev => prev + 1);
}
});
if (loader.current) observer.observe(loader.current);
return () => {
if (loader.current) observer.unobserve(loader.current);
};
}, [hasMore]);
return (
<div style={{ padding: '1rem' }}>
<h2>Infinite Scroll Posts</h2>
<ul>
{posts.map(post => (
<li key={post.id} style={{ marginBottom: '1rem' }}>
<strong>{post.title}</strong>
<p>{post.body}</p>
</li>
))}
</ul>
{hasMore && <div ref={loader}>Loading more...</div>}
</div>
);
};
export default InfiniteScroll;
Modify App.js to use your infinite scroll component:
import React from 'react';
import InfiniteScroll from './InfiniteScroll';
function App() {
return (
<div className="App">
<InfiniteScroll />
</div>
);
}
export default App;
posts, page, and hasMore track content and pagination.fetchPosts: Fetches 10 items per page and appends them to the list.IntersectionObserver: Observes a div at the bottom of the list. When it enters the viewport, the page state increments, triggering new data fetch.You can replace the Loading more... line with a spinner or skeleton placeholder using a library like react-loading-skeleton or your own CSS.
With IntersectionObserver and a bit of state management, infinite scroll becomes a powerful and performant user experience feature. This pattern works for feeds, product listings, comment sections, and more.
Technology, Web3
April 29, 2025
Read More