This website uses cookies to ensure you get the best experience on our website.

Skip to content
LOGO
  • Company

    About IGNEK

    Learn about our story and our mission.

    Careers

    We're hiring!

    We always looking for talented peoples. Join our team!

    Blogs

    The latest industry news, updates and info.

    Case Studies

    Take a closer look at the projects we've delivered

    Webinar

    Watch our latest organized webinar

    Get in touch with our HR team

    • hr@ignek.com
    • +91 93284 95160
    • Ahmedabad, Gujarat, India – 382470
  • Services

    Enterprise Portal Development

    Custom Enterprise Portal Development for flawless Solutions

    Dedicated Development Team

    Expand Teams, Optimize Development with Our Expertise

    Back-end Development

    Empowering your digital presence with robust backend development expertise

    Front-end Development

    Crafting engaging user experiences through expert frontend development

    Digital Transformation

    Embrace digital transformation by modernizing process

    SaaS Development

    Transform your business with SaaS Innovative Solutions

    Technologies

    Liferay Services

    Development & Customization

    Theme

    Upgradation

    Migration

    Proof of Concept

    Performance Tunning

    Architecture

    Support & Maintenance

    E-commerce

    Expert Advice

    React Services

    Enterprise Development

    Custom Application

    Single Page Application

    Architecture

    API Integration

    Migration

    Consulting

    Maintenance & Support

    Spring Boot Services

    Web Service

    MVC Web Development

    API Integration

    Security

    Migration

    Microservices

    Support & Maintenance

    AEM Services

    Consulting Service

    Site Development

    Migration & Upgradation

    Integration

    Maintenance & Support

    Custom Solutions

    Content Management

    Team Augementation

  • Solution

    Ready for digital excellence

    In our rapidly evolving world, businesses are always on the lookout for fresh ways to improve their operations and connect with their audiences.

    Contact US

    Solutions

    SaaS : Software As A Service

    Transforming industries through cutting edge SaaS solutions.

    Customer Portal : Boost Business Productivity

    Streamline operations and enhance productivity with our Customer Portal solution.

    Liferay Based Intranet Portal

    Internal portal for company communication, collaboration and resources

    Integration

    Matomo Integration with Liferay

    Integrate Matomo to enable user interactions seamlessly.

    Microsoft Teams integration with Liferay

    Integrate to enable seamless collaboration, messaging within your portal.

    Jira Integration With Liferay

    Optimizes business operations by integrating with Jira.

  • Hire Us

    Liferay

    Get expert Liferay developers for seamless portal solutions.

    React JS

    Get expert ReactJS developers for dynamic web solutions.

    Web Developer

    Get custom web solutions from IGNEK's expert developers.

    Spring Boot

    Get top-notch Spring Boot developers for your project success!

    Healthcare

    Get top Healthcare Developers for cutting-edge medical software.

    MERN Stack

    Get expert MERN developers from IGNEK for custom, innovative project solutions.

    Why Hire Developers From IGNEK ?

    • Certified Developer
    • Transparent Communication
    • Flexible Hiring Modals
    • Fully Signed NDA
    • Cost Effective
    • Easy Exit Policy

    Get in touch with our Sales team

    • sales@ignek.com
    • +91 6351576580
    • info@ignek.com
    • Ahmedabad, Gujarat, India – 382470
SCHEDULE CALL
  • COMPANY
    • About
    • Case Studies
    • Blogs
    • Career
    • Webinar
  • SERVICES
    • Enterprise Portal Development
    • Dedicated Development Team
    • Back-end Development
    • Front-end Development
    • Digital Transformation
    • SaaS Development
  • SOLUTION
    • Customer Portal:  Boost Business Productivity
    • SaaS : Software as a Service
    • Liferay Based Employee Intranet Portal
  • TECHNOLOGY
    • Liferay Services
      • Liferay Development and Customization
      • Liferay Theme Development Service
      • Liferay DXP 7.4 Upgrade
      • Liferay Migration
      • Liferay Proof Of Concept
      • Liferay Performance Tuning
      • Liferay Architecture Design Service
      • Liferay Support And Maintenance Service
      • Liferay Ecommerce Development
      • Liferay Expert Advice
    • ReactJS Services
      • ReactJS Enterprise Application Development
      • ReactJS Custom Application Development
      • ReactJS Single Page Application Development (SPA)
      • ReactJS Applications Architecture
      • ReactJS API Integration
      • ReactJS Migration
      • ReactJS Consulting
      • ReactJS Maintenance and Support
    • Spring Boot Services
      • Spring Boot Web Development Service
      • Spring MVC Web Development
      • Spring Boot API Integration Service
      • Spring Boot Security
      • Spring Boot Migration Service
      • Spring Boot Microservices
      • Spring Boot Support & Maintenance Service
    • AEM Development Services
      • AEM Consulting Services
      • AEM Site Development
      • AEM Migration & Upgradation
      • AEM Integration Services
      • AEM Maintenance & Support
      • AEM Content Management
      • Custom AEM Solutions
      • AEM Team Augmentation
  • INTEGRATION
  • HIRE US
    • Hire Liferay Developer
    • Hire ReactJS Developer
    • Hire Spring Boot Developer
    • Hire Healthcare Developer
    • Hire Web Developer
    • Hire MERN Stack Developer
  • CONTACT US
  • Company

    About IGNEK

    Careers

    We're hiring!

    Blogs

    Case Studies

    Webinar

    Get in touch with our HR team

    • hr@ignek.com
    • +91 93284 95160
    • Ahmedabad, Gujarat, India – 382470
  • Services

    Enterprise Portal Development

    Dedicated Development Team

    Back-end Development

    Front-end Development

    Digital Transformation

    SaaS Development

    Technologies

    Liferay Liferay Services
    • Development & Customization
    • Theme
    • Upgradation
    • Migration
    • Proof of Concept
    • Performance Tuning
    • Architecture
    • Support & Maintenance
    • E-commerce
    • Expert Advice
    React React Services
    • Enterprise Development
    • Custom Application
    • Single Page Application
    • Architecture
    • API Integration
    • Migration
    • Consulting
    • Maintenance & Support
    Spring Boot Spring Boot Services
    • Web Service
    • MVC Web Development
    • API Integration
    • Security
    • Migration
    • Microservices
    • Support & Maintenance
    AEM AEM Services
    • Consulting Service
    • Site Development
    • Migration & Upgradation
    • Integration
    • Maintenance & Support
    • Custom Solutions
    • Content Management
    • Team Augmentation
  • Solution

    Ready for digital excellence

    In our rapidly evolving world, businesses are always on the lookout for fresh ways to improve their operations and connect with their audiences.

    Contact US

    Solutions

    SaaS : Software As A Service

    Customer Portal : Boost Business Productivity

    Liferay Based Intranet Portal

    Integration

    Matomo Integration with Liferay

    Microsoft Teams integration with Liferay

    Jira Integration With Liferay

  • Hire Us

    Liferay

    React JS

    Web Developer

    Spring Boot

    Healthcare

    MERN Stack

    Why Hire Developers From IGNEK ?

    • Certified Developer
    • Transparent Communication
    • Flexible Hiring Modals
    • Fully Signed NDA
    • Cost Effective
    • Easy Exit Policy

    Get in touch with our Sales team

    • sales@ignek.com
    • +91 6351576580
    • IGNEK
    • Ahmedabad, Gujarat, India – 382470
  • SCHEDULE CALL

Implement Infinite Scrolling in React by Making a Custom Hook

  • ReactJS
  • July 8, 2025

Share On :

Introduction

Infinite scrolling is a widely used UX pattern to load data as the user scrolls, removing the need for pagination and creating a seamless browsing experience — especially in feeds, search results, and product listings.

In this blog, we will :

  • Understand when infinite scrolling is useful.
  • Learn why the Intersection Observer API is a  better approach than scroll events.
  • Set up a React + TypeScript + Vite project.
  • Use Material UI (MUI) for UI components.
  • Build a reusable custom hook useInfiniteScroll.
  • Integrate infinite scroll into a working component.
What Is Infinite Scrolling?

Infinite scrolling dynamically loads more content as the user scrolls down the page, instead of requiring them to click on pagination buttons like “Next” or “Page 2.”

Common Use Cases :

Use Case

Description

Social media feeds

Facebook, Twitter, Instagram — loads new posts while scrolling

E-commerce products

Product grids auto-load more items (Amazon, Flipkart)

Search results

Loads additional search results (Google Images, YouTube, etc.)

News/Blogs

Loads older articles as you scroll (Medium, Dev.to)

Dashboards

Large tables and data logs

Why Not Just Use Scroll Events?

The traditional way to detect scrolling involves listening to scroll events :

				
					window.addEventListener('scroll', handleScroll);
				
			

This might seem easy, but it introduces several issues :

Limitations of Scroll Events :

  1. Manual Calculations Required
    You must calculate scroll position, total height, and offsets every time.
  2. Performance Issues
    Scroll events fire very frequently — especially during fast scrolling — leading to performance bottlenecks if not throttled.
  3. Hard to Maintain
    Complex logic is needed when dealing with nested or dynamic scroll containers.
  4. Unreliable with Dynamic Content
    Layout changes or lazy-loaded components can cause scroll detection to fail.
Why Use the Intersection Observer API?

The Intersection Observer API is a modern, browser-native feature that lets you observe when an element enters the viewport — without expensive scroll checks.

Advantages :

  • Efficient and performs better than scroll events

  • No manual calculations of scroll position

  • Works with both window scroll and scrollable containers

  • Automatically cleans up when the element is removed

So for this blog, we’ll build our infinite scroll using this powerful and elegant approach.

Step 1: Set Up React + TypeScript with Vite

Run the following commands to initialize your project:

				
					npm create vite@latest infinite-scroll-custom-hook --template react-ts
cd infinite-scroll-custom-hook
npm install

				
			

Step 2 : Install Material UI

				
					npm install @mui/material @emotion/react @emotion/styled
				
			

Step 3 : Create useInfiniteScroll Hook

Create a file: src/hooks/useInfiniteScroll.ts.

				
					//useInfiniteScroll.ts

import { useEffect, useRef } from "react";

interface UseInfiniteScrollProps {
  loadMore: () => void;
  hasMore: boolean;
}

const useInfiniteScroll = ({ loadMore, hasMore }: UseInfiniteScrollProps) => {
  const loadMoreRef = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    if (!hasMore) return;

    const observer = new IntersectionObserver(([entry]) => {
      if (entry.isIntersecting) {
        loadMore();
      }
    });

    if (loadMoreRef.current) {
      observer.observe(loadMoreRef.current);
    }

    return () => observer.disconnect();
  }, [loadMore, hasMore]);

  return loadMoreRef;
};

export default useInfiniteScroll;

				
			

useInfiniteScroll Hook :

This custom hook uses the Intersection Observer API to detect when a hidden div (placed at the bottom of the list) comes into view. When it becomes visible, it automatically calls the loadMore function to fetch more items — as long as hasMore is true.

It returns a ref (loadMoreRef) that you attach to that bottom div, making infinite scrolling smooth and efficient without manual scroll tracking.

Step 4 : Implement in App.tsx

				
					//App.tsx

import { useState, useRef, useCallback } from "react";

import useInfiniteScroll from "./hooks/useInfiniteScroll";

const App = () => {
  const allItems = useRef<string[]>(
    Array.from({ length: 100 }, (_, i) => `Item #${i + 1}`)
  );

  const [visibleItems, setVisibleItems] = useState<string[]>(
    allItems.current.slice(0, 20)
  );
  const [hasMore, setHasMore] = useState(true);
  const [loading, setLoading] = useState(false);

  const loadMoreItems = useCallback(() => {
    if (loading || !hasMore) return;
    setLoading(true);

    setTimeout(() => {
      setVisibleItems((prev) => {
        const nextItems = allItems.current.slice(prev.length, prev.length + 12);
        const updatedItems = [...prev, ...nextItems];

        if (updatedItems.length >= allItems.current.length) {
          setHasMore(false);
        }

        return updatedItems;
      });
      setLoading(false);
    }, 1000);
  }, [loading, hasMore]);

  const loadMoreRef = useInfiniteScroll({ loadMore: loadMoreItems, hasMore });

  return (
    <Box>
      <Box>
        <Typography>
          Infinite Scroll Demo
        </Typography>
        <Typography>
          Scroll down to load more items dynamically
        </Typography>
      </Box>

      <Box>
        {visibleItems.map((item, index) => (
          <Card key={index}>
            <CardContent>
              <Typography>
                {item}
              </Typography>
              <Divider/>
              <Typography>
                This is a demo item rendered using infinite scroll.
              </Typography>
            </CardContent>
          </Card>
        ))}
      </Box>

      {/* Scroll*/}
      <div ref={loadMoreRef}/>

      {loading && (
        <Box>
          <Fade in={loading}>
            <CircularProgress/>
          </Fade>
        </Box>
      )}

      {!hasMore && (
        <Typography>
          You’ve reached the end of the list.
        </Typography>
      )}
    </Box>
  );
};

export default App;

				
			
  • Initial Setup
    • A list of 100 items is created and stored in a ref (allItems). The full list is stored using useRef instead of useState because this data is static and does not change during the component’s lifecycle. Using useRef allows the data to persist across renders without causing re-renders, making it more efficient for holding stable, non-reactive data.
    • The component shows the first 20 items using visibleItems state.
  • State Management
    • visibleItems: Holds the items currently visible on screen.
    • hasMore: Tracks if there are more items to load.
    • loading: Prevents multiple simultaneous load operations.
  • Load More Items Function (loadMoreItems)
    • A useCallback function that runs when the user scrolls to the bottom.
    • It adds 12 more items to the visibleItems list after a 1-second delay (to simulate loading).
    • If all items have been loaded, it sets hasMore to false to stop further loading.
  • Infinite Scroll Hook (useInfiniteScroll)
    • Returns a ref (loadMoreRef) that is placed at the bottom of the page.
    • When this ref becomes visible (i.e., user scrolls near the end), the hook automatically calls loadMoreItems — but only if hasMore is true.
  • Loading & Completion Handling
    • While loading is in progress, a spinner is shown.
    • Once all items are loaded, a message is displayed indicating the end of the list.

Step 5 : Start the App

				
					npm run dev
				
			

Visit the local host in your browser. Scroll to the bottom and watch items load automatically.

Real-World Enhancements

Here’s how you can extend this setup in real-world apps :

Feature

What to Do

API Pagination

Track current page in state and pass it to the loadMore() fetch call

Filtering

Reset list and observer when filters change

Server Sorting

Reset list and sort params, then refetch

Scroll Container

Pass a root option to IntersectionObserver for scrollable divs

Error Handling

Show fallback UI when fetch fails

Output
CONCLUSION

If you’re building infinite scrolling in a React app, using a custom hook with the Intersection Observer API is usually the cleaner choice. It helps you avoid attaching scroll listeners directly, which can lead to messy code and performance issues. Plus, it’s reusable and keeps things organized.

That being said, infinite scroll doesn’t always cover every use case. In situations where users want to jump to a page, apply filters, or sort the data, traditional pagination might work better. The right approach depends on what kind of data you’re dealing with and what the user expects.

Explore Our Services

Discover how we can help your business thrive, whether you’re running a small startup, an SME, or a large enterprise. We’re here to understand your unique needs and goals, offering the expertise and resources to support your journey to success.
Stay informed about our ReactJS services and updates by subscribing to our newsletter—just fill in the details below to subscribe.

Loading
Loading...

Related Blogs

January 24, 2025
Data visualization in React
Data visualization in React : integrating Victory Chart for stunning visuals
March 3, 2025
Implement Infinite Scrolling in React by using Intersection Observers API
Implement Infinite Scrolling in React by using Intersection Observers API
June 25, 2025
How to virtualize large lists using React-Window
Loading...

Featured Projects Portfolios

November 27, 2023
Government Job Platform User-Friendly, Secure and Scalable
Government Job Platform : User-Friendly, Secure, and Scalable
October 4, 2023
Telemedicine Appointment & Health Record Portal
Telemedicine Appointment & Health Record Portal
October 4, 2023
DAM Solution using Liferay Headless Portal Architecture
DAM Solution using Liferay : Headless Portal Architecture

Digital Solutions for Your Business with IGNEK

4.9

5.0

5.0

5.0

LOGO

Making the world a better place through constructing elegant hierarchies

COMPANY

  • About
  • Career
  • Case Study
  • Blogs

SERVICES

  • Enterprise Portal Development
  • Dedicated Development Team
  • Back-end Development
  • Front-end Development
  • Digital Transformation
  • SaaS Development

HIRE US

  • Liferay
  • Spring Boot
  • ReactJS
  • Healthcare
  • MERN Stack
  • AEM

CONTACT

  • info@ignek.com
  • info@ignek.com
SALES
  • sales@ignek.com
  • (+91) 635 157 6580
CAREER
  • hr@ignek.com
  • (+91) 932 849 5160
  • E 910-912, Ganesh Glory 11, Jagatpur Road, SG Highway, Ahmedabad, Gujarat - 382470

© 2018-2025 IGNEK, Inc. All rights reserved

Linkedin Facebook X-twitter Instagram