Pagination and Infinite Scrolling with React Hooks
Last Updated :
09 May, 2024
In the world of web development, making long lists of items like posts, products, or comments easy to navigate is super important. Two common ways to do this are Pagination and Infinite Scrolling. In this guide, we’ll walk through how to implement both of these techniques using React Hooks. Don’t worry if you’re new to React or programming – we’ll take it step by step!
Prerequisite:
Approach to Implement Pagination and Infinite Scrolling with React Hooks
Pagination Approach:
- useState: Utilize the useState hook to manage state variables such as
posts
, loading
, and currentPage
. - useEffect: Fetch data from the API when the
currentPage
changes, using the useEffect hook with a dependency on currentPage
. - Fetch Data: Fetch posts from the API based on the current page using
fetchPosts
function, which updates the posts
state and toggles the loading
state. - Handle Page Change: Implement a
handlePageChange
function to update the currentPage
state when the user navigates between pages. - Render: Render the fetched posts and display a loading indicator while data is being fetched.
Infinite Scroll Approach:
- useState: Similar to pagination, use the useState hook to manage state variables such as
posts
, loading
, page
, and hasMore
. - useEffect: Fetch data from the API when the
page
changes, using the useEffect hook with a dependency on page
. - Fetch Data: Fetch posts from the API based on the current page using
fetchPosts
function, which appends new posts to the existing list and updates the hasMore
state. - Handle Scroll: Implement a
handleScroll
function that triggers when the user scrolls to the bottom of the page. If conditions are met (not loading, more posts available, scrolled to the bottom), increment the page
state. - Render: Render the fetched posts and display a loading indicator while data is being fetched. Also, add a scroll event listener in useEffect to detect scrolling.
Steps to Build a Pagination and Infinite Scrolling With React Hooks
Step 1: Setup a new React App.
npx create-react-app project
Step 2: Navigate to the root directory of your project using the below command.
cd project
Step 3: Check `src` folder.
Inside src folder make changes for Pagination and then for Infinite Scroll. Replace the code inside the App.js.
First we will create Pagination then Infinitescroll. You just have to replace the code of App.js for both.
Pagination
Example: Below is an example of Pagination with React Hooks:
CSS
#root {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
.pagination {
display: flex;
justify-content: center;
}
h3 {
margin: 10px;
}
h1 {
background-color: green;
color: aliceblue;
padding: 10px 20px;
}
JavaScript
import React, {
useState,
useEffect
} from 'react';
import './App.css';
const Pagination = () => {
const [posts, setPosts] = useState([]);
const [loading, setLoading] = useState(true);
const [currentPage, setCurrentPage] = useState(1);
useEffect(() => {
fetchPosts();
}, [currentPage]);
const fetchPosts = async () => {
setLoading(true);
try {
const response = await fetch(
`https://jsonplaceholder.typicode.com/posts?_page=${currentPage}&_limit=10`);
const data = await response.json();
setPosts(data);
} catch (error) {
console.error('Error fetching posts:', error);
} finally {
setLoading(false);
}
};
const handlePageChange = (newPage) => {
setCurrentPage(newPage);
};
return (
<div>
<h1>Pagination</h1>
<div className="posts">
{posts.map(post => (
<div key={post.id} className="post">
<h2>{post.title}</h2>
<p>{post.body}</p>
</div>
))}
{loading && <div>Loading...</div>}
</div>
<div className="pagination" >
<button onClick={() => handlePageChange(currentPage - 1)}
disabled={currentPage === 1}>
Previous
</button>
<h3>
{currentPage}
</h3>
<button onClick={() => handlePageChange(currentPage + 1)}>
Next
</button>
</div>
</div>
);
};
export default Pagination;
Start your application using the following command.
npm start
Output:
Infinite Scrolling
Example: Below is an example of Infinite Scrolling With React Hooks:
CSS
/* Write CSS Here */
h1 {
text-align: center;
background-color: green;
color: white;
padding: 10px 20px;
}
h2 {
color: red;
}
JavaScript
import React, {
useState,
useEffect
} from 'react';
import './App.css';
const InfiniteScroll = () => {
const [posts, setPosts] = useState([]);
const [loading, setLoading] = useState(true);
const [page, setPage] = useState(1);
const [hasMore, setHasMore] = useState(true);
useEffect(() => {
fetchPosts();
}, [page]);
const fetchPosts = async () => {
setLoading(true);
try {
const response = await fetch(
`https://jsonplaceholder.typicode.com/posts?_page=${page}&_limit=10`);
const data = await response.json();
setPosts(prevPosts => [...prevPosts, ...data]);
setHasMore(data.length > 0);
} catch (error) {
console.error('Error fetching posts:', error);
} finally {
setLoading(false);
}
};
const handleScroll = () => {
if (!loading && hasMore &&
window.innerHeight + document.documentElement.scrollTop >=
document.documentElement.scrollHeight - 20) {
setPage(prevPage => prevPage + 1);
}
};
useEffect(() => {
window.addEventListener('scroll', handleScroll);
return () => window.removeEventListener('scroll', handleScroll);
}, [loading, hasMore]);
return (
<div>
<h1>Infinite Scroll</h1>
<div className="posts">
{posts.map(post => (
<div key={post.id} className="post">
<h3>{post.title}</h3>
<p>{post.body}</p>
</div>
))}
<h2>
{loading && <div>Loading...</div>}
</h2>
</div>
</div>
);
};
export default InfiniteScroll;
Output :
Conclusion
And that’s it! You’ve now learned how to implement pagination and infinite scrolling using React Hooks. These techniques are essential for creating user-friendly interfaces for long lists of data. Feel free to experiment with the code and customize it to fit your needs. Happy coding!
Share your thoughts in the comments
Please Login to comment...