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

92.85% Statements 65/70
83.63% Branches 46/55
100% Functions 13/13
92.85% Lines 65/70

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 332 333 334 335 336 337 338 339 340 341 342 343 344 345                                                        1x                                                                                                                                                                                                                                                 263x     263x     263x 263x 263x     263x               263x 263x 263x         263x     263x 97x       263x       263x 111x         263x   33x 33x     33x   33x         33x           33x 32x       33x 16x       33x 6x     6x 6x                 263x 104x       263x   219x         219x           219x 17x       202x         202x 98x     104x     104x 102x           102x       104x 3x 1x 1x     3x 3x 2x 2x   3x 1x 1x           101x     101x 101x 101x 101x                               263x 98x 90x         263x               263x            
import {
  useCallback,
  useEffect,
  useLayoutEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import type {
  UseIntersectionObserverOptions,
  UseIntersectionObserverReturn,
  IntersectionEntry,
  OnChangeCallback,
} from "./types";
import {
  isIntersectionObserverSupported,
  toIntersectionEntry,
  createInitialEntry,
  createNoopRef,
  normalizeThreshold,
} from "./utils";
 
/**
 * useLayoutEffect logs a warning when invoked during server rendering.
 * Fall back to useEffect on the server so the latest-callback ref can still
 * be kept up to date without noise in SSR environments.
 */
const useIsomorphicLayoutEffect =
  typeof window !== "undefined" ? useLayoutEffect : useEffect;
 
/**
 * 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 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 the latest onChange callback in a ref so identity changes don't
  // recreate the observer. Assigned post-commit (never during render) to stay
  // concurrent/StrictMode safe.
  const onChangeRef = useRef<OnChangeCallback | undefined>(onChange);
  useIsomorphicLayoutEffect(() => {
    onChangeRef.current = onChange;
  });
 
  // Track the observed node as state so the observer effect re-runs when the
  // ref callback receives a new element — no manual forceUpdate required.
  const [node, setNode] = useState<Element | null>(null);
 
  // ============ State (triggers re-renders) ============
  const [entry, setEntry] = useState<IntersectionEntry | null>(() =>
    initialIsIntersecting ? createInitialEntry(true, null) : null
  );
 
  // Compute inView from entry state, coercing at the boundary to a strict boolean.
  const inView = entry ? entry.isIntersecting === true : initialIsIntersecting;
 
  // Stabilize the threshold so an inline array (e.g. threshold={[0, 0.5, 1]})
  // does not tear down and recreate the native observer on every render.
  const thresholdKey = useMemo(
    () => JSON.stringify(normalizeThreshold(threshold)),
    [threshold]
  );
 
  // ============ 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 === true) {
          hasTriggeredRef.current = true;
 
          // Unobserve the target
          Eif (observerRef.current && nativeEntry.target) {
            observerRef.current.unobserve(nativeEntry.target);
          }
        }
      });
    },
    [triggerOnce]
  );
 
  // ============ Ref Callback ============
  const ref = useCallback((element: Element | null) => {
    setNode(element);
  }, []);
 
  // ============ 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 (!node) {
      return;
    }
 
    const thresholds = JSON.parse(thresholdKey) as number[];
 
    // Create and observe function
    const createAndObserve = () => {
      observerRef.current = new IntersectionObserver(handleIntersection, {
        threshold: thresholds,
        root,
        rootMargin,
      });
 
      observerRef.current.observe(node);
    };
 
    // 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;
      }
    };
  }, [
    enabled,
    triggerOnce,
    delay,
    thresholdKey,
    root,
    rootMargin,
    handleIntersection,
    isSupported,
    node,
  ]);
 
  // ============ 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,
  };
}