summaryrefslogtreecommitdiff
path: root/apps/web/src/hooks/use-infinite-scroll.ts
blob: 8d6e5fcc1601b9f96ae28b3d7a8301fd99a1d7c6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import { useRef, useCallback } from "react";

interface UseInfiniteScrollOptions {
	onLoadMore: () => void;
	hasMore: boolean;
	isLoading: boolean;
	threshold?: number;
	enabled?: boolean;
}

export function useInfiniteScroll({
	onLoadMore,
	hasMore,
	isLoading,
	threshold = 200,
	enabled = true,
}: UseInfiniteScrollOptions) {
	const scrollAreaRef = useRef<HTMLDivElement>(null);

	const handleScroll = useCallback(
		(event: React.UIEvent<HTMLDivElement>) => {
			if (!enabled) return;

			const { scrollTop, scrollHeight, clientHeight } = event.currentTarget;
			const nearBottom = scrollTop + clientHeight >= scrollHeight - threshold;

			if (nearBottom && hasMore && !isLoading) {
				onLoadMore();
			}
		},
		[onLoadMore, hasMore, isLoading, threshold, enabled],
	);

	return { scrollAreaRef, handleScroll };
}