Intersection Observer API – Web APIs | MDN

React Intersection Observer Examples

The Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document's viewport.

Historically, detecting visibility of an element, or the relative visibility of two elements in relation to each other, has been a difficult task for which solutions have been unreliable and prone to causing the browser and the sites the user is accessing to become sluggish. As the web has matured, the need for this kind of information has grown. Intersection information is needed for many reasons, such as:

  • Lazy-loading of images or other content as a page is scrolled.
  • Implementing "infinite scrolling" web sites, where more and more content is loaded and rendered as you scroll, so that the user doesn't have to flip through pages.
  • Reporting of visibility of advertisements in order to calculate ad revenues.
  • Deciding whether or not to perform tasks or animation processes based on whether or not the user will see the result.

You can read more about the IntersectionObserver here.

Let us proceed and look at examples related to ReactJS.

1. react-intersection-observer-hook

This is a small React hook package to use Insersection Observer declaratively.

By using this hook, you can easily track if a component is visible or not, create lazy loading images, trigger animations on entering or leaving the screen etc.

Live demo is here.

If you want to support the browsers those are not supporting it natively, you can use this polyfill.

Step 1: Installation

npm install react-intersection-observer-hook

Step 2: Usage

Here is a simple code to use the hook. Just pass the ref callback to the component that you want to track its visibility. You can find a more complete code in the example folder.

import React, { useEffect } from 'react';
import { useIntersectionObserver } from 'react-intersection-observer-hook';
// ...

function Example() {
  // <code>useIntersectionObserver</code> returns a tuple.
  // We need to give this <code>ref</code> callback to the node we want to observe.
  // The second item, <code>entry</code> is the response of the initially created <code>IntersectionObserver</code> instance.
  const [ref, { entry }] = useIntersectionObserver();
  const isVisible = entry && entry.isIntersecting;

  useEffect(() => {
    console.log(<code>The component is ${isVisible ? 'visible' : 'not visible'}.</code>);
  }, [isVisible]);

  return <SomeComponentToTrack ref={ref} />;
}

if you have a scrollable container, you can set a root like this:

import React, { useEffect } from 'react';
import { useIntersectionObserver } from 'react-intersection-observer-hook';
// ...

function Example() {
  const [ref, { entry, rootRef }] = useIntersectionObserver();
  const isVisible = entry && entry.isIntersecting;

  useEffect(() => {
    console.log(<code>The component is ${isVisible ? 'visible' : 'not visible'}.</code>);
  }, [isVisible]);

  return (
    <ScrollableContainer
      // We use <code>rootRef</code> callback to set our root node.
      ref={rootRef}
    >
      <SomeComponentToTrack ref={ref} />
    </ScrollableContainer>
  );
}

If you just want to track visibility, you can use useTrackVisibility hook. It has the same API as useIntersectionObserver hook. It just returns additional fields in its second tuple item.

import React, { useEffect } from 'react';
import { useTrackVisibility } from 'react-intersection-observer-hook';
// ...

function Example() {
  // <code>useTrackVisibility</code> also returns a tuple like <code>useIntersectionObserver</code>.
  // First item is the same <code>ref</code> callback to set the node to observe.
  // Second item is an object that we can use to decide if a node is visible.
  // <code>entry</code>: Same object which is returned by <code>useIntersectionObserver</code>.
  // <code>rootRef</code>: Same ref callback which is returned by <code>useIntersectionObserver</code>.
  // <code>isVisible</code>: Becomes true/false based on the response of <code>IntersectionObserver</code>.
  // <code>wasEverVisible</code>: When our observed node becomes visible once, this flag becomes <code>true</code> and stays like that.
  const [
    ref,
    { entry, rootRef, isVisible, wasEverVisible },
  ] = useTrackVisibility();

  useEffect(() => {
    console.log(<code>The component is ${isVisible ? 'visible' : 'not visible'}.</code>);
  }, [isVisible]);

  return <SomeComponentToTrack ref={ref} />;
}

Arguments

Both useIntersectionObserver and useTrackVisibility gets the same arguments. And those are;

  • rootMargin: Indicates the margin value around the root element. Default value is zero for all directions (top, right, bottom and left).
  • threshold: Threshold value (or values) to trigger the observer.

_For more info, you can check here and here._

Reference

Read more here.
An Example is here.
Follow code author here.

Read More.