useInfiniteScroll
Load more when a sentinel intersects.
Import
TypeScript
import { useInfiniteScroll } from '@/hooks';API
Signature
useInfiniteScroll(sentinelRef, { fetcher, ... })
When to use
Feeds and activity streams.
SSR / Next.js
Client-side. Prefer RSC for first-paint server data.
Live playground
Edit the example and see it run against the real @/hooks package in this app.
Live playgroundEdit · run with real
@/hooks · useInfiniteScrollEditor
function Feed() { const sentinel = useRef<HTMLDivElement>(null); const { items, loading, hasMore } = useInfiniteScroll<{ id: number }>(sentinel, { fetcher: async (page) => { const res = await fetch(`/api/items?page=${page}`); return res.json(); }, }); return ( <div> {items.map((i) => <div key={i.id}>{i.id}</div>)} <div ref={sentinel}>{loading ? 'Loading…' : hasMore ? '' : 'End'}</div> </div> ); }
Preview
Implementation source
Full library source for useInfiniteScroll — copy into your project when you are not installing a package yet.
hooks/async/useInfiniteScroll.ts
import { useCallback, useEffect, useState } from 'react';
import type { RefObject } from 'react';
import { useIntersectionObserver } from '../dom/useIntersectionObserver';
import { useIsMounted } from '../utility/useIsMounted';
export interface UseInfiniteScrollOptions<T> {
fetcher: (page: number) => Promise<T[]>;
initialPage?: number;
rootMargin?: string;
enabled?: boolean;
}
/**
* Load more items when a sentinel element intersects the viewport.
*/
export function useInfiniteScroll<T>(
sentinelRef: RefObject<Element | null>,
options: UseInfiniteScrollOptions<T>,
) {
const {
fetcher,
initialPage = 1,
rootMargin = '200px',
enabled = true,
} = options;
const isMounted = useIsMounted();
const [items, setItems] = useState<T[]>([]);
const [page, setPage] = useState(initialPage);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<Error | null>(null);
const [hasMore, setHasMore] = useState(true);
const loadMore = useCallback(async () => {
if (loading || !hasMore || !enabled) return;
setLoading(true);
setError(null);
try {
const next = await fetcher(page);
if (!isMounted()) return;
setItems((prev) => [...prev, ...next]);
setHasMore(next.length > 0);
setPage((p) => p + 1);
} catch (e) {
if (!isMounted()) return;
setError(e instanceof Error ? e : new Error(String(e)));
} finally {
if (isMounted()) setLoading(false);
}
}, [fetcher, page, loading, hasMore, enabled, isMounted]);
const entry = useIntersectionObserver(sentinelRef, {
rootMargin,
enabled: enabled && hasMore && !loading,
});
useEffect(() => {
if (entry?.isIntersecting) {
void loadMore();
}
}, [entry?.isIntersecting, loadMore]);
const reset = useCallback(() => {
setItems([]);
setPage(initialPage);
setHasMore(true);
setError(null);
}, [initialPage]);
return { items, loading, error, hasMore, loadMore, reset, page };
}
Copy-paste example
useInfiniteScroll.example.tsx
'use client';
import { useRef } from 'react';
import { useInfiniteScroll } from '@/hooks';
export function Feed() {
const sentinel = useRef<HTMLDivElement>(null);
const { items, loading, hasMore } = useInfiniteScroll<{ id: number }>(sentinel, {
fetcher: async (page) => {
const res = await fetch(`/api/items?page=${page}`);
return res.json();
},
});
return (
<div>
{items.map((i) => <div key={i.id}>{i.id}</div>)}
<div ref={sentinel}>{loading ? 'Loading…' : hasMore ? '' : 'End'}</div>
</div>
);
}Production checklist
- Called only from Client Components or other custom hooks
- Type parameters filled in (e.g.
useFetch<User[]>) - Tip: Abort in-flight work when the URL changes. Prefer null URL / enabled:false to skip.
- Source of truth: open
hooks/async/useInfiniteScroll.tsfor implementation details