JAVASCRIPT

React `useIntersectionObserver` Hook for Scroll Tracking

Implement lazy loading, infinite scroll, or "in view" tracking efficiently in React with the `useIntersectionObserver` hook, improving performance.

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

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

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

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

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

  return [ref, isIntersecting];
}

// Example Usage:
// function LazyImage({ src, alt }) {
//   const [imgRef, isVisible] = useIntersectionObserver({ threshold: 0.1 });
//   return (
//     <img
//       ref={imgRef}
//       src={isVisible ? src : 'placeholder.jpg'}
//       alt={alt}
//       style={{ minHeight: '200px', background: '#eee' }}
//     />
//   );
// }
How it works: The `useIntersectionObserver` hook provides a clean way to detect when an element enters or exits the viewport. It returns a `ref` to attach to the target element and a boolean `isIntersecting` state. This is highly useful for implementing features like lazy loading images, infinite scrolling, or triggering animations when an element becomes visible, optimizing performance by only rendering or loading content when necessary.

Need help integrating this into your project?

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

Hire DigitalCodeLabs