guarahooks's logo

guarahooks

Command Palette

Search for a command to run...

useIntersectionObserver

A React hook for observing element intersections using the Intersection Observer API

Intersection Observer Demo
Observe when the box enters/exits the viewport.
Not Visible

Intersection Ratio:

Installation

Props

PropTypeDefaultDescription
rootElement  Document  nullnullThe element used as viewport for checking visibility.
rootMarginstring'0px'Margin around the root when calculating intersections.
thresholdnumber  number[]0Percentage(s) of the target's visibility to trigger callback.

Data

PropertyTypeDescription
ref(node: T  null) => voidCallback ref to assign to the target element.
entryIntersectionObserverEntry  nullThe latest observed intersection entry.
isIntersectingbooleanWhether the target is intersecting the root.

Key Features & Details

Browser Support

The Intersection Observer API is widely supported across modern browsers:

  • Chrome: Full support (v58+)
  • Firefox: Full support (v55+)
  • Safari: Full support (v12.1+)
  • Edge: Full support (v16+)
  • Opera: Full support (v45+)

Performance Considerations

  • Offloads intersection detection to the browser for optimized performance.
  • Automatically disconnects when ref is set to null or component unmounts.
  • Supports configurable thresholds and margins.

Best Practices & Caveats

  1. Always assign the returned ref to an element.
  2. Use appropriate thresholds to avoid excessive callbacks.
  3. Consider debouncing when observing multiple elements.
  4. Clean up by setting ref(null) if you want to stop observing early.
  5. Check for API support in older browsers or provide fallbacks.

Examples

Basic Usage

const { ref, entry, isIntersecting } =
  useIntersectionObserver<HTMLDivElement>();
 
return <div ref={ref}>{isIntersecting ? 'Visible' : 'Not visible'}</div>;

With Custom Options

const { ref, entry, isIntersecting } = useIntersectionObserver<HTMLDivElement>({
  root: document.querySelector('#scrollArea'),
  rootMargin: '0px',
  threshold: [0, 0.5, 1.0],
});

Reset Observer

<Button onClick={() => ref(null)}>Reset Observer</Button>

Usage

import { useIntersectionObserver } from '@/hooks/use-intersection-observer';
 
function MyComponent() {
  const { ref, entry, isIntersecting } =
    useIntersectionObserver<HTMLDivElement>({
      threshold: 0.1,
    });
 
  return (
    <div ref={ref}>
      {isIntersecting ? 'In view' : 'Out of view'} (
      {entry?.intersectionRatio.toFixed(2)})
    </div>
  );
}

Common Use Cases

  1. Lazy-loading images as they enter the viewport.
  2. Infinite scrolling pagination.
  3. Triggering animations when elements come into view.
  4. Reporting visibility of ads or analytics.
  5. Virtualizing long lists for performance.