All files / use-resize-observer/src useResizeObserver.ts

83.44% Statements 126/151
75.86% Branches 66/87
69.56% Functions 16/23
86.71% Lines 124/143

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 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428                                                                                                                                                                                                              163x     163x     163x     163x 163x 163x 163x 163x 163x 163x 163x 163x 163x 163x     163x 163x 163x 163x     163x       65x           163x     163x     39x 39x 39x     39x 17x     1x 1x           39x 39x   39x 39x 39x     39x 37x 37x       36x 36x                         163x     45x 3x 3x       45x 45x   45x   8x 4x 4x   37x   8x 8x   8x 4x 4x 4x   3x 2x 2x 2x         29x             163x     163x     163x                                             163x   56x     56x 1x       55x 4x     55x     55x 50x 50x 50x   5x 5x             163x   4x     4x           4x 4x 4x         163x 3x 3x     3x 3x     163x 2x 2x 2x 2x 2x       163x 65x     65x 45x       65x           65x   65x 1x 1x   65x 1x 1x     65x 63x 63x   65x               163x 68x   3x   1x 1x 1x 2x   2x 2x 2x         163x 99x                   163x                                     163x                          
import { useCallback, useEffect, useRef, useState, useMemo } from "react";
import type {
  UseResizeObserverOptions,
  UseResizeObserverReturn,
  ResizeEntry,
  OnResizeCallback,
  OnErrorCallback,
  ResizeObserverBoxOptions,
} from "./types";
import {
  isResizeObserverSupported,
  toResizeEntry,
  extractSize,
  createInitialResizeEntry,
  createNoopRef,
  validateOptions,
  hasSizeChanged,
} from "./utils";
 
/**
 * React hook for observing element size changes using ResizeObserver API.
 *
 * Features:
 * - Real-time element size tracking (width, height)
 * - Support for border-box, content-box, device-pixel-content-box
 * - Debounce/Throttle options for performance optimization
 * - Custom rounding function for dimension values
 * - Callback and state-based modes
 * - SSR compatible with graceful degradation
 * - TypeScript support with full type inference
 *
 * @param options - Configuration options for the observer
 * @returns Object containing dimensions, ref callback, and control methods
 *
 * @example
 * ```tsx
 * // Basic usage - track element dimensions
 * function Component() {
 *   const { ref, width, height } = useResizeObserver();
 *   return (
 *     <div ref={ref}>
 *       Size: {width}px x {height}px
 *     </div>
 *   );
 * }
 * ```
 *
 * @example
 * ```tsx
 * // With debounce for performance
 * function DebouncedComponent() {
 *   const { ref, width, height } = useResizeObserver({
 *     debounce: 100,
 *     onResize: (entry) => console.log('Resized:', entry),
 *   });
 *   return <div ref={ref}>{width} x {height}</div>;
 * }
 * ```
 *
 * @example
 * ```tsx
 * // Border-box sizing
 * function BorderBoxComponent() {
 *   const { ref, borderBoxSize } = useResizeObserver({
 *     box: 'border-box',
 *   });
 *   return (
 *     <div ref={ref} style={{ padding: 20 }}>
 *       Border: {borderBoxSize?.inlineSize} x {borderBoxSize?.blockSize}
 *     </div>
 *   );
 * }
 * ```
 *
 * @example
 * ```tsx
 * // Callback-only mode (no state updates)
 * function CallbackOnlyComponent() {
 *   const { ref } = useResizeObserver({
 *     updateState: false,
 *     onResize: (entry) => {
 *       // Direct DOM manipulation for animations
 *       entry.target.style.setProperty('--width', `${entry.contentRect.width}px`);
 *     },
 *   });
 *   return <div ref={ref}>Animation container</div>;
 * }
 * ```
 */
export function useResizeObserver<T extends Element = Element>(
  options: UseResizeObserverOptions<T> = {}
): UseResizeObserverReturn<T> {
  const {
    box = "content-box",
    debounce,
    throttle,
    round = Math.round,
    onResize,
    onError,
    updateState = true,
    enabled = true,
    initialWidth,
    initialHeight,
  } = options;
 
  // ============ Validation ============
  validateOptions(debounce, throttle);
 
  // ============ SSR Check ============
  const isSupported = isResizeObserverSupported();
 
  // ============ Refs ============
  const observerRef = useRef<ResizeObserver | null>(null);
  const targetRef = useRef<T | null>(null);
  const onResizeRef = useRef<OnResizeCallback | undefined>(onResize);
  const onErrorRef = useRef<OnErrorCallback | undefined>(onError);
  const debounceRef = useRef<number | undefined>(debounce);
  const throttleRef = useRef<number | undefined>(throttle);
  const debounceTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const throttleTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const lastThrottleTimeRef = useRef<number>(0);
  const isObservingRef = useRef<boolean>(false);
  const prevSizeRef = useRef<{ width: number; height: number } | null>(null);
 
  // Update refs on each render to get latest values
  onResizeRef.current = onResize;
  onErrorRef.current = onError;
  debounceRef.current = debounce;
  throttleRef.current = throttle;
 
  // ============ State ============
  const [state, setState] = useState<{
    width: number | undefined;
    height: number | undefined;
    entry: ResizeEntry | undefined;
  }>(() => ({
    width: initialWidth,
    height: initialHeight,
    entry: createInitialResizeEntry(initialWidth, initialHeight),
  }));
 
  const [isObserving, setIsObserving] = useState<boolean>(false);
 
  // ============ Handle Resize (Core Logic) ============
  const handleResize = useCallback(
    (entries: ResizeObserverEntry[]) => {
      // Process all entries (for multiple element observation)
      for (const entry of entries) {
        try {
          const resizeEntry = toResizeEntry(entry);
 
          // Call onResize callback for each entry
          if (onResizeRef.current) {
            onResizeRef.current(resizeEntry);
          }
        } catch (error) {
          Eif (onErrorRef.current) {
            onErrorRef.current(error as Error);
          }
        }
      }
 
      // Update state with the last entry (for single element mode via ref)
      const lastEntry = entries[entries.length - 1];
      Iif (!lastEntry) return;
 
      try {
        const resizeEntry = toResizeEntry(lastEntry);
        const { width, height } = extractSize(lastEntry, box, round);
 
        // Update state if enabled and size changed
        if (updateState) {
          const prevSize = prevSizeRef.current;
          if (
            !prevSize ||
            hasSizeChanged(prevSize.width, prevSize.height, width, height)
          ) {
            prevSizeRef.current = { width, height };
            setState({ width, height, entry: resizeEntry });
          }
        }
      } catch (error) {
        if (onErrorRef.current) {
          onErrorRef.current(error as Error);
        }
      }
    },
    [box, round, updateState]
  );
 
  // ============ Process Resize (with Debounce/Throttle) ============
  const processResize = useCallback(
    (entries: ResizeObserverEntry[]) => {
      // Clear existing debounce timeout
      if (debounceTimeoutRef.current) {
        clearTimeout(debounceTimeoutRef.current);
        debounceTimeoutRef.current = null;
      }
 
      // Use refs to get latest debounce/throttle values
      const debounceDelay = debounceRef.current ?? 0;
      const throttleInterval = throttleRef.current ?? 0;
 
      if (debounceDelay > 0) {
        // Debounce mode
        debounceTimeoutRef.current = setTimeout(() => {
          handleResize(entries);
          debounceTimeoutRef.current = null;
        }, debounceDelay);
      } else if (throttleInterval > 0) {
        // Throttle mode
        const now = Date.now();
        const timeSinceLastCall = now - lastThrottleTimeRef.current;
 
        if (timeSinceLastCall >= throttleInterval) {
          lastThrottleTimeRef.current = now;
          handleResize(entries);
        } else if (!throttleTimeoutRef.current) {
          // Schedule trailing call
          throttleTimeoutRef.current = setTimeout(() => {
            lastThrottleTimeRef.current = Date.now();
            handleResize(entries);
            throttleTimeoutRef.current = null;
          }, throttleInterval - timeSinceLastCall);
        }
      } else {
        // No debounce/throttle - immediate execution
        handleResize(entries);
      }
    },
    [handleResize]  // Remove debounce/throttle from deps - use refs instead
  );
 
  // ============ Observer Callback ============
  const observerCallbackRef = useRef<(entries: ResizeObserverEntry[]) => void>(
    (entries) => processResize(entries)
  );
  observerCallbackRef.current = (entries) => processResize(entries);
 
  // ============ Create Observer ============
  const createObserver = useCallback(() => {
    if (!isSupported) return;
 
    // Disconnect existing observer
    if (observerRef.current) {
      observerRef.current.disconnect();
      observerRef.current = null;
    }
 
    // Create new observer with ref-based callback for stability
    observerRef.current = new ResizeObserver((entries) => {
      observerCallbackRef.current(entries);
    });
 
    // Observe current target if exists and enabled
    if (targetRef.current && enabled) {
      observerRef.current.observe(targetRef.current, { box });
      isObservingRef.current = true;
      setIsObserving(true);
    }
  }, [isSupported, enabled, box]);
 
  // ============ Ref Callback ============
  const setRef = useCallback(
    (node: T | null) => {
      const prevTarget = targetRef.current;
 
      // Skip if same element (prevent redundant observe calls)
      if (node === prevTarget) {
        return;
      }
 
      // Unobserve previous target
      if (prevTarget && observerRef.current) {
        observerRef.current.unobserve(prevTarget);
      }
 
      targetRef.current = node;
 
      // Observe new target
      if (node && observerRef.current && enabled) {
        observerRef.current.observe(node, { box });
        isObservingRef.current = true;
        setIsObserving(true);
      } else {
        isObservingRef.current = false;
        setIsObserving(false);
      }
    },
    [box, enabled]
  );
 
  // ============ Manual Control Methods ============
  const observe = useCallback(
    (element: T) => {
      Iif (!isSupported) return;
 
      // Create observer if it doesn't exist yet
      Iif (!observerRef.current) {
        observerRef.current = new ResizeObserver((entries) => {
          observerCallbackRef.current(entries);
        });
      }
 
      observerRef.current.observe(element, { box });
      isObservingRef.current = true;
      setIsObserving(true);
    },
    [isSupported, box]
  );
 
  const unobserve = useCallback((element: T) => {
    Iif (!observerRef.current) return;
    observerRef.current.unobserve(element);
    // Check if still observing other elements
    // For simplicity, we set to false (single element mode)
    isObservingRef.current = false;
    setIsObserving(false);
  }, []);
 
  const disconnect = useCallback(() => {
    Iif (!observerRef.current) return;
    observerRef.current.disconnect();
    observerRef.current = null;
    isObservingRef.current = false;
    setIsObserving(false);
  }, []);
 
  // ============ Effect: Create Observer on Mount ============
  useEffect(() => {
    Iif (!isSupported) return;
 
    // Create observer with ref-based callback (only once on mount)
    observerRef.current = new ResizeObserver((entries) => {
      observerCallbackRef.current(entries);
    });
 
    // Observe current target if exists and enabled
    Iif (targetRef.current && enabled) {
      observerRef.current.observe(targetRef.current, { box });
      isObservingRef.current = true;
      setIsObserving(true);
    }
 
    return () => {
      // Cleanup timeouts
      if (debounceTimeoutRef.current) {
        clearTimeout(debounceTimeoutRef.current);
        debounceTimeoutRef.current = null;
      }
      if (throttleTimeoutRef.current) {
        clearTimeout(throttleTimeoutRef.current);
        throttleTimeoutRef.current = null;
      }
      // Disconnect observer
      if (observerRef.current) {
        observerRef.current.disconnect();
        observerRef.current = null;
      }
      isObservingRef.current = false;
    };
    // Note: Only depend on isSupported to create observer once on mount
    // enabled and box changes are handled separately to avoid re-creating observer
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isSupported]);
 
  // ============ Effect: Handle enabled toggle ============
  useEffect(() => {
    if (!isSupported || !observerRef.current || !targetRef.current) return;
 
    if (enabled && !isObservingRef.current) {
      // Only observe if not already observing
      observerRef.current.observe(targetRef.current, { box });
      isObservingRef.current = true;
      setIsObserving(true);
    E} else if (!enabled && isObservingRef.current) {
      // Only unobserve if currently observing
      observerRef.current.unobserve(targetRef.current);
      isObservingRef.current = false;
      setIsObserving(false);
    }
  }, [enabled, isSupported, box]);
 
  // ============ Computed Values ============
  const computedValues = useMemo(
    () => ({
      contentRect: state.entry?.contentRect,
      borderBoxSize: state.entry?.borderBoxSize?.[0],
      contentBoxSize: state.entry?.contentBoxSize?.[0],
      devicePixelContentBoxSize: state.entry?.devicePixelContentBoxSize?.[0],
    }),
    [state.entry]
  );
 
  // ============ SSR Return ============
  Iif (!isSupported) {
    return {
      ref: createNoopRef<T>(),
      width: initialWidth,
      height: initialHeight,
      entry: createInitialResizeEntry(initialWidth, initialHeight),
      contentRect: undefined,
      borderBoxSize: undefined,
      contentBoxSize: undefined,
      devicePixelContentBoxSize: undefined,
      isSupported: false,
      isObserving: false,
      observe: () => {},
      unobserve: () => {},
      disconnect: () => {},
    };
  }
 
  // ============ Client Return ============
  return {
    ref: setRef,
    width: state.width,
    height: state.height,
    entry: state.entry,
    ...computedValues,
    isSupported,
    isObserving,
    observe,
    unobserve,
    disconnect,
  };
}