Hi developers, Welcome to this article. Infinite scrolling is a popular technique in today's time, by using which we can increase user engagement. With this, users don't need to click on pagination buttons to see more content. Instead, new content loads automatically as they scroll down the page.
You might have noticed that as we scroll on platforms like Instagram and YouTube, new content gets loaded without clicking on any button, so this is possible with infinite scrolling technology.
Before we begin, make sure you have the following prerequisites.
Prerequisites:
- Basic knowledge of React, JavaScript, and React Hooks
- Node.js installed on your machine
To implement infinite scrolling with React Hooks, follow these steps:
Step 1: Set Up Your React Application
Step 2: Create the InfiniteScroll Component
Step 3: Integrate the InfiniteScroll Component
Step 4: Run and Test Your Application
Step 1: Set Up Your React Application
If you already have a project and want to add infinite scrolling, start from Step 2. If you're practicing and need to create a project, first set up a new React application using the Create React App.
npx create-react-app infinite-scroll-app
cd infinite-scroll-app
npm start
Step 2: Create the InfiniteScroll Component
Create a new file named InfiniteScroll.jsx in the src directory. This component will handle the infinite scroll logic and fetch data from a public API.
Fetching Data:
We will use the Fetch API to get data from the public API to get new content when the user scrolls down. For this project, we will be using the JSONPlacefolder API.
import React, { useState, useEffect, useRef, useCallback } from 'react';
const fetchData = async (page) => {
const response = await fetch(`https://jsonplaceholder.typicode.com/posts?_page=${page}&_limit=10`);
const data = await response.json();
return data;
};
Building the Infinite Scroll Logic:
Here's the full component code with the logic to handle infinite scrolling:
// InfiniteScroll.jsx
import React, { useState, useEffect, useRef, useCallback } from 'react';
// Fetch data function with error handling
const fetchData = async (page) => {
try {
const response = await fetch(`https://jsonplaceholder.typicode.com/posts?_page=${page}&_limit=10`);
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
return data;
} catch (error) {
console.error('Fetch error:', error);
return [];
}
};
const InfiniteScroll = () => {
const [items, setItems] = useState([]);
const [hasMore, setHasMore] = useState(true);
const [page, setPage] = useState(1);
const [loading, setLoading] = useState(false);
const observer = useRef();
useEffect(() => {
const fetchItems = async () => {
setLoading(true);
const newItems = await fetchData(page);
setItems(prevItems => [...prevItems, ...newItems]);
setHasMore(newItems.length > 0);
setLoading(false);
};
fetchItems();
}, [page]);
const lastItemRef = useCallback(node => {
if (observer.current) observer.current.disconnect();
observer.current = new IntersectionObserver(entries => {
if (entries[0].isIntersecting && hasMore && !loading) {
setPage(prevPage => prevPage + 1);
}
});
if (node) observer.current.observe(node);
}, [hasMore, loading]);
return (
<div className="container">
{items.map((item, index) => (
<div
key={item.id}
ref={items.length === index + 1 ? lastItemRef : null}
className="item"
>
{item.title}
</div>
))}
{loading && <div className="loading">Loading...</div>}
</div>
);
};
export default InfiniteScroll;
Step 3: Integrate the InfiniteScroll Component
Next, integrate the InfiniteScroll component into your main application component. Modify the App.js file as follows:
// App.js
import React from 'react';
import InfiniteScroll from './InfiniteScroll.jsx';
import './App.css';
const App = () => {
return (
<div className="app">
<h1>Infinite Scroll Demo</h1>
<InfiniteScroll />
</div>
);
};
export default App;
For better presentation, add some basic CSS to style the items, container, and loading indicator. Modify the App.css file as follows:
/* App.css */
.app {
text-align: center;
}
.container {
display: flex;
flex-direction: column;
align-items: center;
}
.item {
background-color: #f0f0f0;
margin: 5px 0;
padding: 15px;
border-radius: 5px;
width: 400px;
text-align: left;
}
.loading {
font-size: 1.2em;
margin: 20px 0;
color: #333;
}
Step 4: Run and Test Your Application
Run your React application using the following command:
npm start
View your project in the browser. As you scroll down the page, you'll notice the infinite scroll feature in action. Additionally, a loading indicator will appear at the bottom of the page while new items are being fetched from the API.
Conclusion
We've seen how simple it is to add infinite scroll to a React app using React hooks. While many developers use the "react infinite scroll component" library for this, it's essential to understand different methods for doing the same work if you want to become a skilled developer.
If you want to make this project even more attractive, you can add additional features like a good loading spinner, error handling, and more advanced data capture techniques.
If you have any questions about this article or related to web development, you can ask them in the question box given below, and you will get the answer as soon as possible.