JAVASCRIPT

Custom Hook for Element Visibility (useOnScreen)

Create a versatile React custom hook to detect when a specific DOM element enters or exits the viewport using the Intersection Observer API, enabling lazy loading and animations.

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

function useOnScreen(ref, rootMargin = '0px') {
  // State and setter for storing whether element is visible
  const [isIntersecting, setIntersecting] = useState(false);

  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => {
        // Update our state when observer callback fires
        setIntersecting(entry.isIntersecting);
      },
      {
        rootMargin,
      }
    );
    if (ref.current) {
      observer.observe(ref.current);
    }

    return () => {
      observer.unobserve(ref.current);
    };
  }, []); // Empty array ensures that effect is only run on mount and unmount

  return isIntersecting;
}

// Example usage:
// function LazyImage({ src, alt }) {
//   const imgRef = useRef();
//   const isVisible = useOnScreen(imgRef, '100px'); // 100px before it comes into view

//   return (
//     <div style={{ height: '300px', marginBottom: '20px', background: '#eee' }}>
//       <img
//         ref={imgRef}
//         src={isVisible ? src : ''} // Load image only when visible
//         alt={alt}
//         style={{ opacity: isVisible ? 1 : 0, transition: 'opacity 0.5s', maxWidth: '100%' }}
//       />
//       {!isVisible && <p style={{ textAlign: 'center' }}>Scroll down to see image</p>}
//     </div>
//   );
// }
How it works: The `useOnScreen` hook leverages the browser's Intersection Observer API to determine if a referenced DOM element is currently visible within the viewport. It returns a boolean `isIntersecting` value which updates as the element scrolls into or out of view. This is incredibly useful for implementing features like lazy loading of images or components, triggering animations when elements appear, or tracking analytics based on element visibility, enhancing performance and user experience.

Need help integrating this into your project?

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

Hire DigitalCodeLabs