Member-only story
Infinite Loading UI in React without library
with Intersection Observer API
What is Intersection Observer?
Intersection Observer is a Web API that allows you to efficiently detect when an HTML element enters or exits the viewport or another specified element. It provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with the browser viewport.
The Intersection Observer API works by creating an observer object that watches for changes to the target element’s intersection with a root element, which is typically the browser viewport. The observer is created using the IntersectionObserver()
constructor, which takes a callback function as its argument.
The callback function is called whenever the observed element intersects with the root element or its own ancestor elements, and it receives an array of IntersectionObserverEntry
objects as its argument. Each IntersectionObserverEntry
object provides information about the observed element's intersection with the root element, including the element's bounding rectangle, the intersection ratio, and whether the element is currently intersecting with the root element.
Here’s an example of how to use the Intersection Observer API to detect when an element enters or exits…