← Back to all snippets
JAVASCRIPT

Implementing a `useIntersectionObserver` Hook

Create a custom React `useIntersectionObserver` hook for efficient lazy loading, infinite scrolling, or animations by detecting element visibility.

import { useRef, useState, useEffect } from 'react';

function useIntersectionObserver(options) {
  const [entry, setEntry] = useState(null);
  const [node, setNode] = useState(null); // The DOM element to observe

  const observer = useRef(null);

  useEffect(() => {
    if (observer.current) {
      observer.current.disconnect();
    }

    observer.current = new IntersectionObserver(([ent]) => setEntry(ent), options);

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

    return () => {
      if (observer.current) {
        observer.current.disconnect();
      }
    };
  }, [node, options]); // Re-run if observed node or options change

  return [setNode, entry];
}

// Example Usage:
// function MyComponent() {
//   const [setRef, entry] = useIntersectionObserver({ threshold: 0.1 });
//   const isVisible = entry?.isIntersecting;

//   return (
//     <div style={{ height: '100vh', background: 'lightblue' }}>Scroll down</div>
//     <div
//       ref={setRef}
//       style={{
//         height: '100vh',
//         background: isVisible ? 'lightgreen' : 'lightcoral',
//         display: 'flex',
//         alignItems: 'center',
//         justifyContent: 'center',
//         fontSize: '2em'
//       }}
//     >
//       {isVisible ? 'I am visible!' : 'Scroll to see me'}
//     </div>
//   );
// }
How it works: This custom hook wraps the browser's `IntersectionObserver` API. It allows components to efficiently detect when a specified DOM element enters or exits the viewport, or crosses a certain threshold of visibility, returning an `IntersectionObserverEntry` object.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs