Infinite list with max pages
A product list that loads more as you scroll, but never holds more than three pages. Scroll down and the top pages are dropped. Scroll back up and they are fetched again. The bar at the top shows which pages are loaded and how many requests were sent.
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
import { useEffect, useRef } from "react";
/**
* Calls `onVisible` while the element is near the viewport. `watch` creates a new observer after every change,
* and a new observer reports the current state at once, so a still visible element triggers again.
*/
export const useInView = <T extends Element>(
onVisible: () => void,
{ enabled, watch }: { enabled: boolean; watch: unknown },
) => {
const ref = useRef<T>(null);
const callback = useRef(onVisible);
useEffect(() => {
callback.current = onVisible;
});
useEffect(() => {
const element = ref.current;
if (!element || !enabled) return undefined;
const observer = new IntersectionObserver(([entry]) => entry?.isIntersecting && callback.current(), {
rootMargin: "200px",
});
observer.observe(element);
return () => observer.disconnect();
}, [enabled, watch]);
return ref;
};
npx tiged BetterTyped/hyper-fetch/examples/react/infinite-max-pages hyper-fetch-react-infinite-max-pages && cd hyper-fetch-react-infinite-max-pages && npm install && npm run devmaxPages: 3onuseInfiniteFetchkeeps the list at three pages. Loading one at one end drops one at the other.fetchPreviousPageloads the page before the first loaded one, so the list works in both directions.- A spacer keeps the scroll position steady while pages above are dropped and loaded again.
- Live status: loaded page numbers, the visible item range and a request counter.
How it works
-
api.tssets 20 products per page and describes the dummyjson paging:offset: "skip",limit: "limit",items: "products"andtotal: "total". With an offset, the hook can compute both the next and the previous page. -
App.tsxpassesmaxPagesto the hook:const list = useInfiniteFetch(getProductsRequest, { pagination: productsPagination, maxPages: 3 });When
fetchNextPage()adds a fourth page, the first one is dropped andhasPreviousPagebecomestrue. WhenfetchPreviousPage()brings it back, the last page is dropped instead. -
pageParamsholds theskipof every loaded page.pageParams[0]is the index of the first item on screen. -
Dropping pages at the top would move the rest of the list up. A spacer with the height of the dropped rows (
firstIndex * rowHeight) takes their place, so what you are looking at stays where it is. The rows have a fixed height for this reason. -
useInViewwatches the spacer and a sentinel below the list. When the spacer comes into view, the page before is fetched. When the sentinel comes into view, the next page is fetched. After a failed page, a Try again button calls the same function. -
A dropped page is fetched from the network again. The request counter goes up when you scroll back.
maxPagestrades requests for a smaller list, so pick a page size that is taller than the screen.
- Long feeds, logs or tables where people scroll far and memory or render time starts to matter.
- Combine it with a virtualized list when rows have different heights. Then the virtualizer gives you the offsets instead of a fixed row height.
Related
maxPages caps how many pages useInfiniteFetch keeps, and fetchPreviousPage loads the dropped ones back. A spacer
with the height of the dropped rows keeps scrolling smooth in both directions.
