|
| 1 | +import { useEffect, useRef, useState, useCallback, RefObject } from 'react'; |
| 2 | +import { buildRootMargin } from './utils/buildRootMargin'; |
| 3 | + |
| 4 | +export interface UseInfiniteScrollOptions { |
| 5 | + /** |
| 6 | + * Called when the sentinel enters the viewport. Append new items to your |
| 7 | + * list state, do not replace the existing items. |
| 8 | + */ |
| 9 | + next: () => void; |
| 10 | + /** |
| 11 | + * Whether more data exists to load. Set to false when you have fetched all |
| 12 | + * pages, the observer disconnects and stops calling next(). |
| 13 | + */ |
| 14 | + hasMore: boolean; |
| 15 | + /** |
| 16 | + * Total number of items currently rendered. Resets the load guard so the |
| 17 | + * next page can be triggered after new items arrive. Pass the length of |
| 18 | + * your full accumulated list, not just the current page. |
| 19 | + */ |
| 20 | + dataLength: number; |
| 21 | + /** |
| 22 | + * How close to the sentinel before next() fires. |
| 23 | + * - Number 0–1: fraction of container height, e.g. 0.8 triggers at 80%. |
| 24 | + * - Pixel string: absolute offset, e.g. "200px" triggers 200 px before end. |
| 25 | + * @default 0.8 |
| 26 | + */ |
| 27 | + scrollThreshold?: number | string; |
| 28 | + /** |
| 29 | + * A scrollable parent element (or its DOM id string) to use as the |
| 30 | + * IntersectionObserver root. Defaults to the viewport when omitted. |
| 31 | + */ |
| 32 | + scrollableTarget?: HTMLElement | string | null; |
| 33 | + /** |
| 34 | + * Reverse scroll direction, sentinel is observed from the top. Use for |
| 35 | + * chat or messaging UIs with flex-direction: column-reverse. |
| 36 | + * @default false |
| 37 | + */ |
| 38 | + inverse?: boolean; |
| 39 | +} |
| 40 | + |
| 41 | +export interface UseInfiniteScrollResult { |
| 42 | + /** |
| 43 | + * Attach this ref to a div at the bottom of your list (or top for inverse |
| 44 | + * mode). When it enters the viewport the hook calls next(). |
| 45 | + * |
| 46 | + * @example |
| 47 | + * <ul> |
| 48 | + * {items.map(item => <li key={item.id}>{item.name}</li>)} |
| 49 | + * <li ref={sentinelRef} /> |
| 50 | + * </ul> |
| 51 | + */ |
| 52 | + sentinelRef: RefObject<HTMLDivElement | null>; |
| 53 | + /** |
| 54 | + * True from when the sentinel fires until dataLength changes (i.e. new |
| 55 | + * data has arrived). Use this to show your own loading indicator. |
| 56 | + */ |
| 57 | + isLoading: boolean; |
| 58 | +} |
| 59 | + |
| 60 | +/** |
| 61 | + * Low-level hook for building custom infinite scroll UIs. |
| 62 | + * |
| 63 | + * Manages an IntersectionObserver that watches a sentinel element you place |
| 64 | + * at the end of your list. When the sentinel enters the viewport, next() is |
| 65 | + * called. The hook handles deduplication and resets automatically when |
| 66 | + * dataLength changes. |
| 67 | + * |
| 68 | + * Use the InfiniteScroll component instead if you want a ready-made wrapper |
| 69 | + * with built-in loader, endMessage, pull-to-refresh, and inverse scroll UI. |
| 70 | + * |
| 71 | + * @example Basic usage |
| 72 | + * ```tsx |
| 73 | + * function Feed() { |
| 74 | + * const [items, setItems] = useState(initialItems); |
| 75 | + * const [hasMore, setHasMore] = useState(true); |
| 76 | + * |
| 77 | + * const { sentinelRef, isLoading } = useInfiniteScroll({ |
| 78 | + * next: async () => { |
| 79 | + * const more = await fetchItems(items.length); |
| 80 | + * if (more.length === 0) { setHasMore(false); return; } |
| 81 | + * setItems(prev => [...prev, ...more]); |
| 82 | + * }, |
| 83 | + * hasMore, |
| 84 | + * dataLength: items.length, |
| 85 | + * }); |
| 86 | + * |
| 87 | + * return ( |
| 88 | + * <ul> |
| 89 | + * {items.map(item => <li key={item.id}>{item.name}</li>)} |
| 90 | + * <li ref={sentinelRef} aria-hidden /> |
| 91 | + * {isLoading && <li>Loading...</li>} |
| 92 | + * </ul> |
| 93 | + * ); |
| 94 | + * } |
| 95 | + * ``` |
| 96 | + */ |
| 97 | +export function useInfiniteScroll({ |
| 98 | + next, |
| 99 | + hasMore, |
| 100 | + dataLength, |
| 101 | + scrollThreshold = 0.8, |
| 102 | + scrollableTarget, |
| 103 | + inverse = false, |
| 104 | +}: UseInfiniteScrollOptions): UseInfiniteScrollResult { |
| 105 | + const [isLoading, setIsLoading] = useState(false); |
| 106 | + const sentinelRef = useRef<HTMLDivElement>(null); |
| 107 | + const actionTriggeredRef = useRef(false); |
| 108 | + |
| 109 | + // Stable ref so the observer callback always calls the latest next() |
| 110 | + // without triggering observer reconnection when an inline function is passed. |
| 111 | + const nextRef = useRef(next); |
| 112 | + nextRef.current = next; |
| 113 | + |
| 114 | + const getScrollableNode = useCallback((): HTMLElement | null => { |
| 115 | + if (scrollableTarget instanceof HTMLElement) return scrollableTarget; |
| 116 | + if (typeof scrollableTarget === 'string') { |
| 117 | + return document.getElementById(scrollableTarget); |
| 118 | + } |
| 119 | + return null; |
| 120 | + }, [scrollableTarget]); |
| 121 | + |
| 122 | + // Reset the load guard when new data arrives. |
| 123 | + useEffect(() => { |
| 124 | + actionTriggeredRef.current = false; |
| 125 | + setIsLoading(false); |
| 126 | + }, [dataLength]); |
| 127 | + |
| 128 | + // IntersectionObserver lifecycle. |
| 129 | + useEffect(() => { |
| 130 | + if (!hasMore) return; |
| 131 | + if (typeof IntersectionObserver === 'undefined') return; |
| 132 | + |
| 133 | + const sentinel = sentinelRef.current; |
| 134 | + if (!sentinel) return; |
| 135 | + |
| 136 | + const root: Element | null = getScrollableNode(); |
| 137 | + |
| 138 | + const observer = new IntersectionObserver( |
| 139 | + ([entry]) => { |
| 140 | + if (!entry.isIntersecting || actionTriggeredRef.current) return; |
| 141 | + actionTriggeredRef.current = true; |
| 142 | + setIsLoading(true); |
| 143 | + nextRef.current(); |
| 144 | + }, |
| 145 | + { |
| 146 | + root, |
| 147 | + rootMargin: buildRootMargin(scrollThreshold, inverse), |
| 148 | + threshold: 0, |
| 149 | + } |
| 150 | + ); |
| 151 | + |
| 152 | + observer.observe(sentinel); |
| 153 | + return () => observer.disconnect(); |
| 154 | + }, [hasMore, scrollThreshold, inverse, getScrollableNode]); |
| 155 | + |
| 156 | + return { sentinelRef, isLoading }; |
| 157 | +} |
0 commit comments