Simple Guide to Using Intersection Observer API with ReactJS

Sachin Chaurasiya - May 16 - - Dev Community

The Intersection Observer API is a new web tool that helps developers check when an element in the DOM comes into or leaves the viewport. This is very useful for lazy loading images, infinite scrolling, and other important features that need to know when an element is visible to the user.

In this article, we'll learn how to use the Intersection Observer API with React, a popular JavaScript library for building user interfaces. We'll start by briefly covering the basics of the Intersection Observer API and its benefits. Then, we'll look at a practical example of using it with React to animate a component.

What is the Intersection Observer API?

The Intersection Observer API is a web tool that lets developers track when an element in the DOM enters or leaves the viewport or a specified parent element. Simply put, it helps us know when an element appears or disappears on the user's screen.

One of the main benefits of using the Intersection Observer API is that it offers a more efficient way to track the visibility of elements in the DOM compared to methods like using scroll or resize event listeners. The Intersection Observer API uses a callback-based approach, which means we can set a function to run when an element's visibility changes, instead of constantly checking visibility on each scroll or resize event.

Using the Intersection Observer API with React

To use the Intersection Observer API with React, we can make a custom hook that simplifies using the Intersection Observer API. This hook can be used in any React component to check if an element is visible and take action when it appears.

Here is an example of a custom useElementInView hook that uses the Intersection Observer API to check if an element is visible

const useElementInView = (options) => {
  const [isInView, setIsInView] = useState(false);
  const targetRef = useRef(null);

  useEffect(() => {
    const observer = new IntersectionObserver((entries) => {
      const [entry] = entries;
      setIsInView(entry.isIntersecting);
    }, options);

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

    return () => {
      if (targetRef.current) {
        observer.unobserve(targetRef.current);
      }
    };
  }, [options]);

  return [targetRef, isInView];
};
Enter fullscreen mode Exit fullscreen mode

This hook creates an IntersectionObserver instance and watches the target element. When the target element becomes visible within the root element, it updates the state with the visibility info.

To use this hook in a React component, you can pass the options to the hook and get the returned ref and visibility info

const MyComponent = () => {
  const [targetRef, isInView] = useElementInView({ threshold: 0.5 });

  return (
    <div ref={targetRef}>
      {isInView ? 'Element is in view!' : 'Element is not in view.'}
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

Alright, we have discussed what the Intersection Observer is and how it works. We created a hook called useElementInView, and in the next section, we will use this hook to animate a component.

Scroll to reveal using the useElementInView hook

We will create a component that will animate an element when it comes into view, essentially a scroll-to-reveal animation.

import React from 'react';
import useElementInView from './useElementInView';

const AnimatedComponent = () => {
  const [targetRef, isInView] = useElementInView({ threshold: 0.1 });

  return (
    <div
      ref={targetRef}
      style={{
        opacity: isInView ? 1 : 0,
        transition: 'opacity 0.5s ease-out',
      }}
    >
      I fade in when scrolled into view!
    </div>
  );
};

export default AnimatedComponent;
Enter fullscreen mode Exit fullscreen mode

In this example, the AnimatedComponent starts with an opacity of 0, making it invisible. When at least 10% of the component scrolls into view (as set by the threshold option), the isInView state changes to true, and the component fades in with an opacity of 1.

Conclusion

In this article, we explore the Intersection Observer API and how to use it with React to track when elements are visible in the viewport. We cover the basics of the API, its advantages over older methods, and show a practical example by creating a custom React hook, useElementInView, to animate components when they come into view.

That's all for this topic. Thank you for reading! If you found this article helpful, please consider liking, commenting, and sharing it with others.

Connect with me

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player