A lightweight, highly optimized
IntersectionObserverhook for flawlessly handling infinite scrolling in React applications.
- Zero Dependencies: Uses native robust browser APIs (
IntersectionObserver). - Highly Performant: No scroll event listeners! Completely eliminates scroll-jank.
- Easy to Use: Simply attach a
refto your last element, and provide a callback. - SSR Safe: Perfectly safe for Next.js, Remix, and standard React SSR environments.
Just drop index.js into your hooks directly or npm install react-infinite-scroll-hook (if published).
import React, { useState } from 'react';
import useInfiniteScroll from './useInfiniteScroll';
function ItemList() {
const [items, setItems] = useState([1, 2, 3, 4, 5]);
const [loading, setLoading] = useState(false);
const loadMore = () => {
if (loading) return;
setLoading(true);
// Simulate API call
setTimeout(() => {
setItems((prev) => [...prev, prev.length + 1, prev.length + 2, prev.length + 3]);
setLoading(false);
}, 1000);
};
const [lastElementRef] = useInfiniteScroll(loadMore, {
rootMargin: '100px', // start loading before the user reaches the exact bottom
});
return (
<div>
{items.map((item, index) => {
// Attach ref to the final item in the loop
if (items.length === index + 1) {
return <div ref={lastElementRef} key={index}>Item {item}</div>;
}
return <div key={index}>Item {item}</div>;
})}
{loading && <p>Loading more items...</p>}
</div>
);
}Infinite scrolling, when poorly implemented, can destroy performance scores (Core Web Vitals) due to heavy DOM operations bound to traditional scroll events. By utilizing the Hardware-Accelerated IntersectionObserver API, we guarantee buttery smooth 60fps scrolling, ensuring Google rewards your site with top tier algorithmic ranks.
If you found this tool useful, check out our other high-performance web utilities and follow Ahmar Hussain for more open-source excellence.
- Stackaura Hub - The central index for all 100 repositories.
- Free LLM APIs - A curated list of zero-cost AI endpoints.
- Awesome MCP Servers - The ultimate collection of Model Context Protocol implementations.
- System Design Cheatsheet - Master complex architectures in minutes.
- Next.js SaaS Starter - The fastest way to launch your next product.
- Website: stackaura.com
- LinkedIn: Ahmar Hussain
- Facebook: Ahmar Hussain
- GitHub: @RanaAhmar