October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk5 min

How to Load the Next Page in a React Feed with a Sentinel

Use an IntersectionObserver sentinel to trigger paginated data loading in React, with lifecycle cleanup, duplicate-request protection, and a clear stopping condition.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Build infinite scroll in React by observing a small sentinel after the loaded items, then requesting another page when that sentinel enters the viewport or a scrollable container. IntersectionObserver detects visibility; your component or data layer still handles fetching, pagination, duplicate-request prevention, errors, and deciding when the feed ends.

What the component needs to manage

Keep pagination and rendering state separate from the observer. The data source supplies pages or cursors; the observer only signals when more data may be needed.

As an Amazon Associate I earn from qualifying purchases.

  • Items: the pages accumulated so far.
  • Page or cursor: the position to request next, as defined by the data source.
  • Loading and error state: whether a request is pending and whether it failed.
  • Has-more state: whether the data source indicates another page exists.

The example below uses a page-based API that returns {"items": [...], "nextPage": 2}, or null for nextPage when no more pages remain. Adapt the response handling to your API; IntersectionObserver does not provide pagination or fetch data.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How to build the observer in React

Place a stable sentinel element after the list and attach a ref to it. Set up the observer in an effect, check isIntersecting, and disconnect it during cleanup. This example also uses a ref as an immediate request lock: state updates are asynchronous, so checking only a loading state may not prevent two callbacks from starting overlapping requests.

#1 Best Overall
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB
  • CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
  • WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
  • A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents
import { useCallback, useEffect, useRef, useState } from "react";

export default function InfiniteList() {
  const [items, setItems] = useState([]);
  const [nextPage, setNextPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const sentinelRef = useRef(null);
  const requestInFlight = useRef(false);

  const loadMore = useCallback(async () => {
    if (!hasMore || requestInFlight.current) return;

    requestInFlight.current = true;
    setLoading(true);
    setError(null);

    try {
      const response = await fetch(`/api/items?page=${nextPage}`);
      if (!response.ok) throw new Error("Could not load more items.");

      const page = await response.json();
      setItems((current) => [...current, ...page.items]);
      setNextPage(page.nextPage ?? nextPage + 1);
      setHasMore(page.nextPage != null);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Could not load more items.");
    } finally {
      requestInFlight.current = false;
      setLoading(false);
    }
  }, [hasMore, nextPage]);

  useEffect(() => {
    const sentinel = sentinelRef.current;
    if (!sentinel || !hasMore) return;

    const observer = new IntersectionObserver((entries) => {
      const entry = entries.find((item) => item.target === sentinel);
      if (entry?.isIntersecting) loadMore();
    });

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

  return (
    <section aria-busy={loading}>
      <ul>
        {items.map((item) => (
          <li key={item.id}>{item.title}</li>
        ))}
      </ul>

      {hasMore && <div ref={sentinelRef} aria-hidden="true" />}
      {loading && <p>Loading more items…</p>}
      {error && (
        <p role="alert">
          {error} <button onClick={loadMore}>Retry</button>
        </p>
      )}
      {!hasMore && <p>You’ve reached the end.</p>}
    </section>
  );
}

Replace the URL, response shape, item fields, and page/cursor updates with those used by your service. The code assumes the server returns a non-null nextPage when more pages exist and null when the feed is exhausted. If your API signals completion differently, derive hasMore from that signal.

How to choose the observer root and trigger point

By default, the observer measures intersection against the document viewport. For a separately scrolling panel, set root to that panel’s DOM element; the sentinel must be inside the root. A positive bottom rootMargin expands the effective bounds so loading can start before the sentinel reaches the visible edge.

Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB
  • CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
  • SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
Use case Observer setting Effect
Page scrolls normally Omit root or set it to null Measures intersection against the viewport.
Content scrolls inside a panel Set root to the scrollable element Measures intersection against that element; the sentinel must be its descendant.
Start loading before the boundary Use a positive bottom value in rootMargin Expands the effective root bounds in the margin direction.

The default threshold is zero, which triggers when the target intersects or touches the root boundary. A threshold of 1.0 requires the entire target to be visible; for a tiny sentinel, that can delay the request until it is fully in view. See MDN’s Intersection Observer API reference for the observer options and intersection behavior.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How to handle repeated triggers, errors, and the end of the feed

A sentinel can stay intersecting across renders, and an observer callback can run again while a request is pending. Keep the request guard inside the fetching function, not only in the observer callback. Update accumulated items and the cursor only after a successful response; on failure, retain a retry path instead of leaving the sentinel unable to make progress.

Rank #3
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
  • Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
  • Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
  • In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
  • Ultra-thin bezels: Maximize your viewing experience with thin bezels.

When the data source says there are no more pages, update hasMore to false and stop observing the sentinel. The example’s effect cleanup disconnects the previous observer whenever its dependencies change and when the component unmounts. React describes effects as the mechanism for synchronizing with external systems and cleaning up that synchronization; see the useEffect reference.

If a request should be cancelled when the component unmounts or the query changes, add an AbortController and abort it in cleanup. The example omits cancellation because its purpose is to show the observer and request guard; a guard prevents duplicate active requests but does not cancel a request already sent.

Rank #4
Sale
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor | 100Hz, Game Mode, Advanced Eye Comfort, HDMI and D-sub Ports (LS27D366GANXZA)
  • CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
  • SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
  • MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
  • KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
  • INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

When to consider windowing

Infinite loading limits how much data is fetched at one time, but it does not limit how many accumulated rows remain rendered. React’s performance guide recommends windowing for long lists—described there as hundreds or thousands of rows—so that only a subset is rendered at once. That range is an example, not a universal cutoff: measure your application and consider a compatible windowing library if rendering the accumulated list becomes costly. Fetch pagination and windowing solve different problems. See React’s guide to virtualizing long lists.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When a scroll listener makes sense

A scroll listener can suit a special case that needs scroll-specific behavior, but its handler may fire frequently. Avoid expensive work in it. MDN advises using IntersectionObserver when threshold-based detection fits, and notes that wrapping a scroll handler in requestAnimationFrame alone does not meaningfully throttle it. If a listener is necessary, use measured timeout throttling as appropriate. See MDN’s scroll event guidance.

Best Value
Sale
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
  • 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
  • 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.

Feedback and accessibility

Keep loading, failure, retry, and end-of-feed feedback visible and meaningful, and ensure that any retry control works with a keyboard. The observer pattern does not replace those interface states. The implementation should follow the accessibility requirements of your product; no single announcement pattern is established here as mandatory for every infinite-scroll component.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.