Provides a shared, module-level `IntersectionObserver` hook that efficiently detects when an element approaches the viewport, firing once and unobserving on first intersection. ## Key Components ### Constants & Module-Level Singletons - **`NEAR_VIEWPORT_ROOT_MARGIN`** — Default lookahead distance (`'500px'`); exported as SSOT for viewport-proximity logic across the codebase. - **`observers`** — `Map` keyed by `rootMargin|threshold`; one IO per unique config, shared across all subscribers. - **`subscribers`** — `WeakMap void>` mapping observed elements to their callbacks; avoids memory leaks on unmount. - **`THRESHOLD_EPSILON`** — Float rounding slack (`0.01`) for sub-pixel `intersectionRatio` comparisons. ### Functions - **`observerKey(rootMargin, threshold)`** — Generates a stable string key for the observer map. - **`getObserverFor(rootMargin, threshold)`** — Returns an existing IO or creates and caches a new one for the given config. ### Hook - **`useNearViewport(rootMargin?, threshold?)`** — Returns `{ ref, isNear }`. Subscribes the attached element to the shared IO; flips `isNear` to `true` once the element meets the threshold, then unobserves. Safe under React StrictMode's double-mount via callback identity checks. ### Interface - **`UseNearViewportResult`** — `{ ref: (node: T | null) => void, isNear: boolean }` ## Usage Example ```typescript import { useNearViewport } from './use-near-viewport'; function LazyCard() { // Start loading 500px before scroll-in (default margin) const { ref, isNear } = useNearViewport(); return
{isNear ? : }
; } function HalfVisibleCard() { // Fire only when at least 50% of the element is on-screen const { ref, isNear } = useNearViewport('0px', 0.5); return
{isNear ? : null}
; } ``` > **Note:** `isNear` is fire-once and never resets. For two-way mount/unmount behavior, use a raw `IntersectionObserver` instead and share `NEAR_VIEWPORT_ROOT_MARGIN` for distance consistency.