DEV Community

Cover image for React Intersection Observer: Detect Elements Entering the Viewport

React Intersection Observer: Detect Elements Entering the Viewport

Key Takeaways

  • Intersection Observer detects when an element enters or leaves the viewport.
  • It is a native browser API that works easily with React.
  • React developers commonly combine it with useRef, useEffect, and useState.
  • Common applications include lazy loading, scroll animations, infinite scrolling, analytics, and video control.
  • threshold controls how much of an element must be visible.
  • rootMargin allows detection before an element reaches the viewport.
  • One observer can monitor multiple elements.
  • Always disconnect the observer when it is no longer required.

Index

  1. Introduction
  2. What Is Intersection Observer?
  3. How It Works
  4. Basic React Example
  5. Important Options
  6. Practical Use Cases
  7. Lazy Loading
  8. Scroll Animations
  9. Infinite Scrolling
  10. Visibility Analytics
  11. Video Control
  12. Reusable Custom Hook
  13. Common Mistakes
  14. Performance Tips
  15. Stats
  16. Interesting Facts
  17. FAQs
  18. Conclusion

1. Introduction

Modern web applications frequently need to know whether an element is visible to the user.

For example:

  • Load an image only when the user approaches it.
  • Start an animation when a section appears.
  • Load more products when the user reaches the bottom.
  • Track whether an advertisement was viewed.
  • Play a video only while it is visible.

One traditional solution is to listen for the scroll event and continuously calculate element positions.

React applications can instead use the browser's Intersection Observer API.

It provides a simple way to react when an element enters or leaves a particular area, usually the browser viewport.

2. What Is Intersection Observer?

Intersection Observer is a browser Web API that allows JavaScript to detect when one element intersects with another element or the viewport.

In simple terms:

Intersection Observer answers the question: "Is this element currently entering, inside, or leaving the visible area?"

For example:

User scrolls
     ↓
Element approaches viewport
     ↓
Intersection detected
     ↓
Callback executes
     ↓
React performs an action
Enter fullscreen mode Exit fullscreen mode

It is useful because developers do not need to repeatedly calculate an element's position during scrolling.

3. How It Works

The basic Intersection Observer flow is:

Create observer
      ↓
Select target element
      ↓
Observe target
      ↓
Element intersects viewport
      ↓
Callback executes
      ↓
Perform required action
Enter fullscreen mode Exit fullscreen mode

Basic JavaScript:

const observer = new IntersectionObserver((entries) => {
    console.log(entries[0].isIntersecting);
});

observer.observe(element);
Enter fullscreen mode Exit fullscreen mode

isIntersecting tells us whether the target is currently intersecting the observer's root.
In React, the same API can be connected to a DOM element using useRef().

4. Basic React Example

A simple React implementation looks like this:

const ref = useRef(null);
const [visible, setVisible] = useState(false);

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

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

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

Enter fullscreen mode Exit fullscreen mode

The reference is attached to the element:

<div ref={ref}>
    {visible ? "Visible" : "Not Visible"}
</div>

Enter fullscreen mode Exit fullscreen mode

What happens?

When the element enters the viewport:
isIntersecting = true

When it leaves:
isIntersecting = false

React can then change the UI, start an animation, request data, or perform another action.

5. Important Intersection Observer Options

Two options are particularly important.

threshold

threshold determines how much of the target should intersect before the observer reports the threshold crossing.

For example:

{ threshold: 0 }
Useful when detecting an element as it begins entering the viewport.

{ threshold: 0.5 }
Useful when approximately half of the element should be visible before taking action.

{ threshold: 1 }
Useful when the target needs to be completely visible for the threshold condition.

Multiple thresholds are also possible:
{ threshold: [0, 0.5, 1] }

rootMargin

rootMargin changes the effective observation area.
Example:
{ rootMargin: "200px" }

This can detect an element before it actually reaches the visible viewport.

This is particularly useful for preloading.

For example:

Image is 200px away
       ↓
Observer detects image
       ↓
Start loading
       ↓
User reaches image
       ↓
Image is ready
Enter fullscreen mode Exit fullscreen mode

6. Practical Use Cases

Intersection Observer is most useful when the requirement is related to visibility.

Common applications

Lazy Loading
Load images or content only when they approach the viewport.

Scroll Animations
Start an animation when a section becomes visible.

Infinite Scrolling
Load the next set of records when the user reaches the bottom.

Analytics
Track when users actually see a particular section or advertisement.

Video Control
Play or pause a video based on its visibility.

On-Demand Content
Fetch expensive data only when the user reaches the relevant section.

7. Practical Example: Lazy Loading

Imagine an e-commerce application containing hundreds of product images.

Loading every image immediately is unnecessary because the user may never scroll far enough to see many of them.

Intersection Observer can detect when an image approaches the viewport.

const observer = new IntersectionObserver(([entry]) => {
    if (entry.isIntersecting) {
        setLoadImage(true);
        observer.disconnect();
    }
}, {
    rootMargin: "200px"
});
Enter fullscreen mode Exit fullscreen mode

The process becomes:

Page loads
   ↓
Image is far away
   ↓
Do nothing
   ↓
User scrolls
   ↓
Image approaches viewport
   ↓
Observer triggers
   ↓
Load image
Enter fullscreen mode Exit fullscreen mode

Where can you use this?

  • E-commerce product lists
  • Image galleries
  • News websites
  • Social feeds
  • Portfolio websites

For basic image lazy loading, native HTML also provides:

Intersection Observer is more useful when custom loading behavior is required.

8. Practical Example: Scroll Animations

Modern websites often animate sections as users scroll.
For example:

Section outside viewport
        ↓
Opacity: 0

User scrolls
        ↓
Section becomes visible
        ↓
Opacity: 1
Enter fullscreen mode Exit fullscreen mode

React can use Intersection Observer to add a CSS class.

const observer = new IntersectionObserver(([entry]) => {
    if (entry.isIntersecting) {
        setVisible(true);
        observer.disconnect();
    }
});
Enter fullscreen mode Exit fullscreen mode

CSS can then handle the animation:

.section {
    opacity: 0;
    transform: translateY(30px);
}

.section.visible {
    opacity: 1;
    transform: translateY(0);
}
Enter fullscreen mode Exit fullscreen mode

*Suitable for : *

  • Landing pages
  • Portfolio websites
  • Corporate websites
  • Product pages
  • Marketing websites

The important idea is to let Intersection Observer detect visibility and CSS handle the animation.

9. Practical Example: Infinite Scrolling

Infinite scrolling is another common use case.

Imagine a product listing:

Product 1
Product 2
Product 3
...
Product 20

       Sentinel
Enter fullscreen mode Exit fullscreen mode

A small element called a sentinel is placed at the bottom.

When the sentinel enters the viewport:

Sentinel visible
      ↓
Request next page
      ↓
Receive products
      ↓
Add products
      ↓
Sentinel moves downward
Enter fullscreen mode Exit fullscreen mode

Example:

const observer = new IntersectionObserver(([entry]) => {
    if (entry.isIntersecting) {
        loadMoreProducts();
    }
}, {
    rootMargin: "300px"
});
Enter fullscreen mode Exit fullscreen mode

Where can you use it?

  • Social media feeds
  • E-commerce listings
  • Search results
  • News feeds
  • Video feeds

In production, also manage loading states so multiple API requests are not triggered simultaneously.

10. Practical Example: Visibility Analytics

Suppose a page contains an advertisement.
Simply rendering the advertisement does not necessarily mean the user saw it.

Intersection Observer can detect when it becomes visible.

const observer = new IntersectionObserver(([entry]) => {
    if (entry.isIntersecting) {
        trackAdView();
        observer.disconnect();
    }
}, {
    threshold: 0.5
});
Enter fullscreen mode Exit fullscreen mode

Here, the application can use a visibility threshold appropriate to its analytics requirements.

The same approach can be used for:

  • Advertisement impressions
  • Product visibility
  • Article sections
  • Marketing content
  • Feature usage

11. Practical Example: Video Control

Intersection Observer can also control media based on visibility.

For example:

Video enters viewport
       ↓
Play

Video leaves viewport
       ↓
Pause
Enter fullscreen mode Exit fullscreen mode

Example:

const observer = new IntersectionObserver(([entry]) => {
    if (entry.isIntersecting) {
        video.play();
    } else {
        video.pause();
    }
}, {
    threshold: 0.5
});
Enter fullscreen mode Exit fullscreen mode

This can be useful for:

  • Short-video feeds
  • Product videos
  • Educational websites
  • Social media interfaces

Browser autoplay policies still need to be considered when automatically playing videos.

12. Reusable Custom Hook

If Intersection Observer is used throughout a React project, creating a custom hook can avoid repeated code.

A simplified hook can look like:

function useIntersectionObserver(options) {
    const ref = useRef(null);
    const [visible, setVisible] = useState(false);

    useEffect(() => {
        if (!ref.current) return;

        const observer = new IntersectionObserver(
            ([entry]) => setVisible(entry.isIntersecting),
            options
        );

        observer.observe(ref.current);

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

    return [ref, visible];
}
Enter fullscreen mode Exit fullscreen mode

A component can then use:

const [ref, visible] = useIntersectionObserver({
    threshold: 0.2
});
Enter fullscreen mode Exit fullscreen mode

This is useful when many components need the same visibility behavior.

Benefits

  • Less duplicated code
  • Easier maintenance
  • Reusable logic
  • Cleaner React components

13. Common Mistakes

Forgetting Cleanup
Always disconnect the observer when the component is removed.
return () => observer.disconnect();

Creating Unnecessary Observers
If multiple elements need to be monitored, one observer can often observe multiple targets.
observer.observe(element1);
observer.observe(element2);
observer.observe(element3);

Triggering API Calls Repeatedly
For infinite scrolling or data loading, protect against duplicate requests.

For example:

Already loading?
↓
Yes → Don't request again
No → Start request

Using Intersection Observer for Everything
It is designed for intersection and visibility.
It is not a replacement for:

  • click
  • mousemove
  • keydown
  • Drag and drop
  • General event handling

14. Performance Tips

Use rootMargin intelligently

For example:
rootMargin: "200px"
can provide extra time for content to load before it becomes visible.

Disconnect one-time observers
If an action only needs to happen once:
observer.disconnect();
or:
observer.unobserve(element);

Avoid unnecessary React state updates
Only update state when the visibility change affects the application.

Combine it with other optimizations
Intersection Observer works well alongside:

  • Image optimization
  • Pagination
  • Code splitting
  • Native lazy loading
  • API caching
  • Virtualized lists

15. Stats

16. Interesting Facts

  • Framework Independent: Intersection Observer is a native JavaScript API that works with React, Vue, Angular, and plain JavaScript.
  • Multiple Elements: A single observer instance can monitor multiple elements, making it useful for lists, cards, and page sections.
  • Early Detection: The rootMargin option can detect elements before they enter the viewport, enabling content preloading.
  • Multiple Use Cases: Beyond animations, Intersection Observer supports lazy loading, analytics, infinite scrolling, and media playback control.
  • Native Lazy Loading: For simple image lazy loading, the browser's built-in loading="lazy" attribute may be sufficient. Intersection Observer is more useful when custom application logic is needed.

17. FAQs

What is Intersection Observer?
It is a browser API that detects when an element enters or leaves an observation area such as the viewport.

Is Intersection Observer part of React?
No. It is a browser API that can be integrated into React using hooks.

What is isIntersecting?
It indicates whether the observed element is currently intersecting the observer's root.

What is threshold?
It controls the intersection ratio at which the observer reports a threshold crossing.

What is rootMargin?
It changes the effective observation area and can allow detection before an element actually enters the viewport.

Can Intersection Observer be used for infinite scrolling?
Yes. A sentinel at the bottom of a list can trigger the next API request.

Can it be used for animations?
Yes. It can add a CSS class when an element becomes visible.

Can it lazy-load images?
Yes. However, native loading="lazy" may be sufficient for basic image loading.

Can one observer monitor multiple elements?
Yes. A single observer can monitor multiple targets.

Should I create a custom hook?
If your project uses Intersection Observer in several components, a custom hook can make the code cleaner and reusable.

18. Conclusion

Intersection Observer provides a simple solution for a common frontend requirement:

"Do something when this element becomes visible."

Instead of continuously calculating element positions during scrolling, developers can let the browser report intersection changes.

The basic React pattern is:

useRef()
   ↓
DOM element
   ↓
IntersectionObserver
   ↓
Intersection detected
   ↓
React state/action
Enter fullscreen mode Exit fullscreen mode

Its most common applications include:

  • Lazy loading
  • Scroll animations
  • Infinite scrolling
  • Analytics
  • Video control
  • On-demand API requests

The two options developers should understand first are:
threshold
rootMargin

For reusable applications, a custom React hook can further simplify the implementation.

Intersection Observer is therefore an important API for React developers who want to build interfaces that load, animate, or react to content based on what the user is actually seeing.

Quotes

“The best optimization is often the work you don't perform until it is actually needed.”

“Great web experiences deliver the right content at the right moment.”

“Performance is not only about doing things faster; it is also about avoiding unnecessary work.”

Top comments (0)