Interview frequency: …
Short answer
Create a Hook that watches a target element (Sentinel Ref) at the bottom of the list and automatically loads more data when it intersects the viewport.
Explanation
Use IntersectionObserver inside useEffect and disconnect it when the component unmounts to detect when the last item appears. Pass states such as hasMore and isLoading to prevent repeated network requests while one is pending or after all data has been loaded.
Code example
function useInfiniteScroll(onLoadMore: () => void, hasMore: boolean, loading: boolean) {
const sentinelRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!hasMore || loading) return;
const observer = new IntersectionObserver(([entry]) => {
if (entry.isIntersecting) {
onLoadMore();
}
});
if (sentinelRef.current) observer.observe(sentinelRef.current);
return () => observer.disconnect();
}, [onLoadMore, hasMore, loading]);
return sentinelRef;
}Common mistakes
- Listening directly to the window scroll event without throttling, heavily consuming the CPU.
Follow-up questions
- How do you build a Custom Hook for LocalStorage with synchronization across browser windows?
- How do you build a Custom Hook to debounce values or function calls and cancel earlier operations?