Ask any question about Web Development here... and get an instant response.
Post this Question & Answer:
How can I implement infinite scrolling with React and a REST API?
Asked on Apr 30, 2026
Answer
To implement infinite scrolling in React with a REST API, you'll need to dynamically load more data as the user scrolls down. This is typically achieved by listening to the scroll event and fetching additional data when the user reaches the bottom of the page. You can use React hooks for state management and lifecycle methods to handle the data fetching.
<!-- BEGIN COPY / PASTE -->
import React, { useState, useEffect, useCallback } from 'react';
const InfiniteScrollComponent = () => {
const [items, setItems] = useState([]);
const [page, setPage] = useState(1);
const [loading, setLoading] = useState(false);
const fetchItems = useCallback(async () => {
setLoading(true);
const response = await fetch(`https://api.example.com/items?page=${page}`);
const data = await response.json();
setItems(prevItems => [...prevItems, ...data]);
setLoading(false);
}, [page]);
useEffect(() => {
fetchItems();
}, [fetchItems]);
const handleScroll = () => {
if (window.innerHeight + document.documentElement.scrollTop !== document.documentElement.offsetHeight || loading) return;
setPage(prevPage => prevPage + 1);
};
useEffect(() => {
window.addEventListener('scroll', handleScroll);
return () => window.removeEventListener('scroll', handleScroll);
}, [handleScroll, loading]);
return (
<div>
{items.map(item => (
<div key={item.id}>{item.name}</div>
))}
{loading && <p>Loading...</p>}
</div>
);
};
export default InfiniteScrollComponent;
<!-- END COPY / PASTE -->Additional Comment:
- Ensure your API supports pagination and returns data based on the page number.
- Consider implementing a debounce or throttle mechanism to optimize the scroll event listener.
- Handle edge cases such as API errors or no more data to load gracefully.
- Test the component across different browsers to ensure consistent behavior.
Recommended Links:
