All files / use-intersection-observer/src useIntersectionObserver.ts

92.95% Statements 66/71
84.21% Branches 48/57
100% Functions 11/11
92.95% Lines 66/71

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331                                                                                                                                                                                                                                                                          251x     251x     251x 251x 251x 251x     251x           251x 251x     251x     251x 94x       251x     251x   32x 32x     32x   32x         32x           32x 31x       32x 16x       32x 6x     6x 6x                 251x   101x     101x     101x 97x         251x   213x         213x           213x 17x       196x         196x 95x     101x     101x 99x           99x 99x         101x 3x 1x 1x     3x 3x 2x 2x   3x 1x 1x           98x     98x 98x 98x 98x                                   251x 95x 87x         251x               251x            
import { useCallback, useEffect, useRef, useState } from "react";
import type {
  UseIntersectionObserverOptions,
  UseIntersectionObserverReturn,
  IntersectionEntry,
  OnChangeCallback,
} from "./types";
import {
  isIntersectionObserverSupported,
  toIntersectionEntry,
  createInitialEntry,
  createNoopRef,
} from "./utils";
 
/**
 * A React hook for observing element visibility using the Intersection Observer API.
 *
 * Features:
 * - Efficient viewport/container visibility detection
 * - Threshold-based intersection callbacks
 * - TriggerOnce support for lazy loading patterns
 * - Dynamic enable/disable support
 * - SSR compatible with graceful degradation
 * - TypeScript support with full type inference
 *
 * @param options - Configuration options for the observer
 * @returns Object containing entry data, inView boolean, and ref callback
 *
 * @example
 * ```tsx
 * // Basic usage - check if element is visible
 * function Component() {
 *   const { ref, inView } = useIntersectionObserver();
 *   return (
 *     <div ref={ref}>
 *       {inView ? 'Visible!' : 'Not visible'}
 *     </div>
 *   );
 * }
 * ```
 *
 * @example
 * ```tsx
 * // Lazy load image when it enters viewport
 * function LazyImage({ src, alt }: { src: string; alt: string }) {
 *   const { ref, inView } = useIntersectionObserver({
 *     triggerOnce: true,
 *     threshold: 0.1,
 *   });
 *
 *   return (
 *     <div ref={ref}>
 *       {inView ? (
 *         <img src={src} alt={alt} />
 *       ) : (
 *         <div className="placeholder" />
 *       )}
 *     </div>
 *   );
 * }
 * ```
 *
 * @example
 * ```tsx
 * // Infinite scroll with sentinel element
 * function InfiniteList() {
 *   const { ref, inView } = useIntersectionObserver({
 *     threshold: 1.0,
 *     rootMargin: '100px',
 *   });
 *
 *   useEffect(() => {
 *     if (inView) {
 *       loadMoreItems();
 *     }
 *   }, [inView]);
 *
 *   return (
 *     <div>
 *       {items.map(item => <Item key={item.id} {...item} />)}
 *       <div ref={ref} />
 *     </div>
 *   );
 * }
 * ```
 *
 * @example
 * ```tsx
 * // Track scroll progress with multiple thresholds
 * function ProgressTracker() {
 *   const { ref, entry } = useIntersectionObserver({
 *     threshold: [0, 0.25, 0.5, 0.75, 1.0],
 *     onChange: (entry, inView) => {
 *       console.log('Progress:', Math.round(entry.intersectionRatio * 100), '%');
 *     },
 *   });
 *
 *   return <div ref={ref}>Long content...</div>;
 * }
 * ```
 *
 * @example
 * ```tsx
 * // Custom scroll container as root
 * function ScrollContainer() {
 *   const containerRef = useRef<HTMLDivElement>(null);
 *   const { ref, inView } = useIntersectionObserver({
 *     root: containerRef.current,
 *     rootMargin: '0px',
 *   });
 *
 *   return (
 *     <div ref={containerRef} style={{ overflow: 'auto', height: 400 }}>
 *       <div style={{ height: 1000 }}>
 *         <div ref={ref}>{inView ? 'In container view' : 'Outside'}</div>
 *       </div>
 *     </div>
 *   );
 * }
 * ```
 */
export function useIntersectionObserver(
  options: UseIntersectionObserverOptions = {}
): UseIntersectionObserverReturn {
  const {
    threshold = 0,
    root = null,
    rootMargin = "0px",
    triggerOnce = false,
    enabled = true,
    initialIsIntersecting = false,
    onChange,
    delay = 0,
  } = options;
 
  // ============ SSR Check ============
  const isSupported = isIntersectionObserverSupported();
 
  // ============ Refs for internal state (no re-renders) ============
  const observerRef = useRef<IntersectionObserver | null>(null);
  const targetRef = useRef<Element | null>(null);
  const hasTriggeredRef = useRef<boolean>(false);
  const delayTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
 
  // Store previous entry values for comparison (to avoid unnecessary re-renders)
  const prevEntryRef = useRef<{
    isIntersecting: boolean;
    intersectionRatio: number;
  } | null>(null);
 
  // Store callbacks in refs to avoid effect dependencies
  const onChangeRef = useRef<OnChangeCallback | undefined>(onChange);
  onChangeRef.current = onChange;
 
  // Force re-render trigger for ref changes
  const [, forceUpdate] = useState({});
 
  // ============ State (triggers re-renders) ============
  const [entry, setEntry] = useState<IntersectionEntry | null>(() =>
    initialIsIntersecting ? createInitialEntry(true, null) : null
  );
 
  // Compute inView from entry state
  const inView = entry?.isIntersecting ?? initialIsIntersecting;
 
  // ============ Observer Callback ============
  const handleIntersection = useCallback(
    (entries: IntersectionObserverEntry[]) => {
      entries.forEach((nativeEntry) => {
        const intersectionEntry = toIntersectionEntry(nativeEntry);
 
        // Check if meaningful values have changed (ignore time which always changes)
        const prevEntry = prevEntryRef.current;
        const hasChanged =
          !prevEntry ||
          prevEntry.isIntersecting !== nativeEntry.isIntersecting ||
          prevEntry.intersectionRatio !== nativeEntry.intersectionRatio;
 
        // Update previous entry ref
        prevEntryRef.current = {
          isIntersecting: nativeEntry.isIntersecting,
          intersectionRatio: nativeEntry.intersectionRatio,
        };
 
        // Only update state if meaningful values changed
        if (hasChanged) {
          setEntry(intersectionEntry);
        }
 
        // Call onChange callback if provided (always call, even if state didn't change)
        if (onChangeRef.current) {
          onChangeRef.current(intersectionEntry, nativeEntry.isIntersecting);
        }
 
        // Handle triggerOnce - unobserve after first intersection
        if (triggerOnce && nativeEntry.isIntersecting) {
          hasTriggeredRef.current = true;
 
          // Unobserve the target
          Eif (observerRef.current && nativeEntry.target) {
            observerRef.current.unobserve(nativeEntry.target);
          }
        }
      });
    },
    [triggerOnce]
  );
 
  // ============ Ref Callback ============
  const setRef = useCallback((node: Element | null) => {
    // Store previous target
    const prevTarget = targetRef.current;
 
    // Update target ref
    targetRef.current = node;
 
    // Force re-render to trigger useEffect with new target
    if (prevTarget !== node) {
      forceUpdate({});
    }
  }, []);
 
  // ============ Effect: Manage Observer Lifecycle ============
  useEffect(() => {
    // SSR guard
    Iif (!isSupported) {
      return;
    }
 
    // Clean up existing observer
    Iif (observerRef.current) {
      observerRef.current.disconnect();
      observerRef.current = null;
    }
 
    // Don't create observer if disabled
    if (!enabled) {
      return;
    }
 
    // Don't create if triggerOnce already triggered
    Iif (triggerOnce && hasTriggeredRef.current) {
      return;
    }
 
    // Don't create if no target
    if (!targetRef.current) {
      return;
    }
 
    const target = targetRef.current;
 
    // Create and observe function
    const createAndObserve = () => {
      observerRef.current = new IntersectionObserver(handleIntersection, {
        threshold,
        root,
        rootMargin,
      });
 
      Eif (target) {
        observerRef.current.observe(target);
      }
    };
 
    // Handle delay
    if (delay > 0) {
      delayTimeoutRef.current = setTimeout(() => {
        createAndObserve();
        delayTimeoutRef.current = null;
      }, delay);
 
      return () => {
        if (delayTimeoutRef.current) {
          clearTimeout(delayTimeoutRef.current);
          delayTimeoutRef.current = null;
        }
        if (observerRef.current) {
          observerRef.current.disconnect();
          observerRef.current = null;
        }
      };
    }
 
    // Create observer immediately
    createAndObserve();
 
    // Cleanup
    return () => {
      Eif (observerRef.current) {
        observerRef.current.disconnect();
        observerRef.current = null;
      }
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [
    enabled,
    triggerOnce,
    delay,
    threshold,
    root,
    rootMargin,
    handleIntersection,
    isSupported,
    // Include target change trigger
    targetRef.current,
  ]);
 
  // ============ Effect: Reset hasTriggered when triggerOnce is disabled ============
  useEffect(() => {
    if (!triggerOnce) {
      hasTriggeredRef.current = false;
    }
  }, [triggerOnce]);
 
  // ============ SSR Return ============
  Iif (!isSupported) {
    return {
      entry: initialIsIntersecting ? createInitialEntry(true, null) : null,
      inView: initialIsIntersecting,
      ref: createNoopRef(),
    };
  }
 
  return {
    entry,
    inView,
    ref: setRef,
  };
}