Infinite scroll
A product list that grows as you scroll. useInfiniteFetch keeps track of the pages, and a small IntersectionObserver
in the app decides when to ask for the next one. A badge in the corner counts the loaded items and pages.
intermediateuseInfiniteFetchpagination
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` when the returned ref's element comes near the viewport.
* Plain IntersectionObserver: HyperFetch has no DOM helpers, so any trigger (observer, button, virtualizer) works.
*/
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;
// A new observer reports the current state right away, so a sentinel that is still visible
// after a short page loads triggers the next page too. `watch` re-creates it after every page.
const observer = new IntersectionObserver(([entry]) => entry?.isIntersecting && callback.current(), {
rootMargin: "300px",
});
observer.observe(element);
return () => observer.disconnect();
}, [enabled, watch]);
return ref;
};
Run locally
npx tiged BetterTyped/hyper-fetch/examples/react/infinite-scroll hyper-fetch-react-infinite-scroll && cd hyper-fetch-react-infinite-scroll && npm install && npm run devWhat it shows
- Typed pagination.
{ offset: "skip", limit: "limit", items: "products", total: "total" }is checked against the request and its response. useInfiniteFetchreturns one flatitemsarray, so there are no pages to merge by hand.- The end of the list is detected from
total, andhasNextPageturnsfalse. - The trigger lives in app code. HyperFetch has no DOM helpers, so the observer is a short hook you own.
How it works
api.tsdefinesgetProductswithlimit,skipandselectquery params, andproductsPaginationwithsatisfies Pagination<typeof getProducts>. A wrong field name is a compile error.AppcallsuseInfiniteFetch(getProducts.setQueryParams({ limit: 12, ... }), { pagination }). The first page starts at offset0, and each next page addslimittoskip.useInViewinuse-in-view.tsobserves an emptydivunder the list with a300pxmargin and callsfetchNextPage()when it comes close to the viewport. It is turned off while a page loads, after a failed page and at the end of the list.- The observer is re-created after every page. A new observer reports the current state at once, so if the list is still too short to fill the screen, the next page loads without any scrolling.
isFetchingNextPageshows the spinner under the list,isFetchNextPageErroroffers a retry, and!hasNextPageshows the end of the list.
const sentinel = useInView<HTMLDivElement>(() => fetchNextPage(), {
enabled: hasNextPage && !isFetchingNextPage && !isFetchNextPageError,
watch: pages.length,
});
Calls to fetchNextPage() made while a page is loading share one request, so a fast scroll never loads the same page
twice.
When to use it
- Feeds, search results and catalogs that users browse rather than page through.
- Mobile layouts, where a "next page" button is easy to miss. For an explicit control, see Load more.
Related
Summary
You described the paging fields once, let useInfiniteFetch merge the pages and detect the end, and loaded each next
page from an IntersectionObserver written in app code.
