We can implement infinite scrolling using the IntersectionObserver API given by browser.
To implement we can simply follow these steps :-
CustomHook.jsx
import axios from "axios"; import { useEffect, useState } from "react"; import { API_URL } from "../common/constants"; export const useAuthorList = (limit, page) => { const [isLoading, setIsLoading] = useState(false); const [authorList, setAuthorList] = useState([]); const [error, setError] = useState(""); const [hasMore, setHasMore] = useState(true); useEffect(() => { setIsLoading(true); setTimeout(() => { axios({ method: "GET", url: API_URL, params: { limit: limit, page: page }, }) .then((res) => { setAuthorList(res.data.data); setHasMore(res.data.data.length === limit); setIsLoading(false); }) .catch((e) => setError(e)); }, 500); }, [limit, page]); return [isLoading, authorList, error, hasMore]; };
App.jsx
import React, { useCallback, useRef, useState } from "react"; import { useAuthorList } from "./hooks/useAuthorList"; import { AuthorQuotes } from "./components/AuthorQuotes"; const App = () => { const [limit, setLimit] = useState(10); const [page, setPage] = useState(1); const [isLoading, authorList, error, hasMore] = useAuthorList(limit, page); const observer = useRef(null); const infiniteReference = useCallback( (element) => { if (isLoading) return; if (observer.current) { observer.current.disconnect(); } observer.current = new IntersectionObserver((entries) => { if (entries[0].isIntersecting && hasMore) { setLimit((prev) => prev + 10); } }); if (element) { observer.current.observe(element); } }, [isLoading, hasMore] ); return ( <div className="author-quotes-list"> {authorList.length > 0 && authorList.map((authorQuotes, index) => { if (index + 1 === authorList.length) { return ( <AuthorQuotes authorQuotes={authorQuotes} hasReference infiniteReference={infiniteReference} /> ); } return <AuthorQuotes authorQuotes={authorQuotes} />; })} {isLoading && <>Loading...</>} </div> ); }; export default App;
constants.js
export const API_URL = "https://api.javascripttutorial.net/v1/quotes/"
The above is the detailed content of Master Infinite Scrolling in Easy Steps. For more information, please follow other related articles on the PHP Chinese website!