DEV Community

Cover image for βš›οΈ React Intersection Observer πŸ‘€ Hook πŸͺ.
alexpaper
alexpaper

Posted on

βš›οΈ React Intersection Observer πŸ‘€ Hook πŸͺ.

As MDN says 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.

It seems complicated but in React you can achieve intersection using a simple hook
the only thing to keep in mind is that you need to pass a 'target element' to the observer
using useRef()

const targetMiddle = React.useRef();
const targetTop = React.useRef();

Enter fullscreen mode Exit fullscreen mode
<h3 ref={targetTop}>TOP</h3>
<h3 ref={targetMiddle}>Middle</h3>

Enter fullscreen mode Exit fullscreen mode

Hook

The hook is very simple
you need to export a function that accept the target element as argument
By default the threshold is set to 0 but you can play around with the options based on your needs
set the state using _isIntersecting _entry property

export function useObserver(ref) {

    const [isIntersecting, setIsIntersecting] = React.useState(false);

     // OPTIONS
     const options = {
        // root: target.current,
        rootMargin: '0px',
        threshold: 0.5, // A threshold of 1.0 means that when 100% of the target is visible within the element specified by the root option, the callback is invoked.
    };
    // Observer
    const observer = new IntersectionObserver(([entry]) => setIsIntersecting(entry.isIntersecting),options);

    // Use Effect
    React.useEffect(() => {

        observer.observe(ref.current)
        // DISCONNECT 
        return () => observer.disconnect()

    }, []);
    // Return
    return isIntersecting
  };

Enter fullscreen mode Exit fullscreen mode

inside useEffect you can call the _disconnect _ method to stop it from observing the target element
and finally return the state that can be true or false,
and based on this value you can change the vDom, for example by showing or hiding a video
when the target element is visible, the limit is your imagination!

In this video guide you can see a super simple implementation, good observation πŸ‘€ ...

Video Guide
πŸ†— πŸ‘‹

Top comments (0)