react-resize-detector

repository·master·Indexed 23 days ago

https://github.com/maslianok/react-resize-detector

A lightweight React library using the native ResizeObserver API to detect element size changes. It provides the useResizeDetector hook and components to integrate dimension-based logic into applications without window resize listeners. Features include support for throttle/debounce rate limiting, options to disable re-renders, and the ability to skip initial mount events.

Tokens
2.4K
Snippets
8
Records
11
Agent score
76%

What's inside react-resize-detector

  1. Performance optimization tips for react-resize-detector

    master

    To ensure high performance when using the library, follow these best practices:

    1. Limit dimension tracking: Use handleWidth: false or handleHeight: false if you only need to monitor one dimension.
    2. Skip initial mount: Use skipOnMount: true if you do not need the initial measurements immediately upon mounting.
    3. Rate limit updates: Use refreshMode: 'debounce' or 'throttle' with a refreshRate for expensive resize handlers (e.g., redrawing charts).
    4. Use disableRerender: If you only need to perform side effects (like updating external state or logging) without triggering a React component re-render, set disableRerender: true and use the onResize callback.
    5. Specify box model: Use observerOptions: { box: 'border-box' } for more consistent and accurate measurements.
  2. Use an external ref with useResizeDetector (Advanced)

    master

    You can observe an element by passing an existing targetRef to the hook.

    Warning: This approach is not advised as dynamically mounting and unmounting the observed element could lead to unexpected behavior.

    import { useRef } from 'react';
    import { useResizeDetector } from 'react-resize-detector';
    
    const CustomComponent = () => {
      const targetRef = useRef<HTMLDivElement>(null);
      const { width, height } = useResizeDetector({ targetRef });
      return <div ref={targetRef}>{`${width}x${height}`}</div>;
    };
  3. Basic usage of useResizeDetector

    master

    The useResizeDetector hook is the primary way to detect element size changes. It returns an object containing the current width, height, and a ref that you must attach to the element you want to observe.

    import { useResizeDetector } from 'react-resize-detector';
    
    const CustomComponent = () => {
      const { width, height, ref } = useResizeDetector<HTMLDivElement>();
      return <div ref={ref}>{`${width}x${height}`}</div>;
    };
  4. Use the onResize callback with useResizeDetector

    master

    You can provide an onResize callback to handle resize events manually. The callback receives a ResizePayload which contains the new dimensions. If the element unmounts, the dimensions will be null.

    import { useCallback } from 'react';
    import { useResizeDetector, OnResizeCallback } from 'react-resize-detector';
    
    const CustomComponent = () => {
      const onResize: OnResizeCallback = useCallback((payload) => {
        if (payload.width !== null && payload.height !== null) {
          console.log('Dimensions:', payload.width, payload.height);
        } else {
          console.log('Element unmounted');
        }
      }, []);
    
      const { width, height, ref } = useResizeDetector<HTMLDivElement>({
        onResize,
      });
    
      return <div ref={ref}>{`${width}x${height}`}</div>;
    };
  5. useResizeDetector API Reference

    master

    Hook Signature

    useResizeDetector<T extends HTMLElement = HTMLElement>(
      props?: useResizeDetectorProps<T>
    ): UseResizeDetectorReturn<T>

    Props

    PropTypeDescriptionDefault
    onResize(payload: ResizePayload) => voidCallback invoked with resize informationundefined
    handleWidthbooleanTrigger updates on width changestrue
    handleHeightbooleanTrigger updates on height changestrue
    skipOnMountbooleanSkip the first resize event when component mountsfalse
    disableRerenderbooleanDisable re-renders triggered by the hook. Only the onResize callback will be calledfalse
    refreshMode'throttle' | 'debounce'Rate limiting strategy.undefined
    refreshRatenumberDelay in milliseconds for rate limiting1000
    refreshOptions{ leading?: boolean; trailing?: boolean }Additional options for throttle/debounceundefined
    observerOptionsResizeObserverOptionsOptions passed to resizeObserver.observeundefined
    targetRefMutableRefObject<T | null>External ref to observe (use with caution)undefined
  6. Reference the useResizeDetector types

    master

    The following types are exported for use in TypeScript applications to ensure type safety when working with the hook's return values, props, and callbacks:

    • UseResizeDetectorReturn: The shape of the object returned by the useResizeDetector hook.
    • useResizeDetectorProps: The configuration options available for the hook.
    • OnResizeCallback: The type for the function called when a resize event occurs.
    • ResizePayload: The data passed to the resize callback.
    • RefreshModeType: Defines how the detector should refresh.
    • RefreshOptionsType: Configuration for the refresh mechanism.
    • Dimensions: The structure of the width and height data.
    export type {
      UseResizeDetectorReturn,
      useResizeDetectorProps,
      OnResizeCallback,
      ResizePayload,
      RefreshModeType,
      RefreshOptionsType,
      Dimensions,
    }
  7. Configure ResizeDetector Props

    master

    When using the useResizeDetector hook or the ResizeDetector component, you can pass a Props object to control how resizing is detected and how the component reacts.

    Key configuration options include:

    • onResize: A callback function invoked with the element's dimensions and the ResizeObserverEntry. If the element unmounts, width and height will be null.
    • handleHeight: Whether to trigger updates on height changes (default: true).
    • handleWidth: Whether to trigger updates on width changes (default: true).
    • skipOnMount: If true, prevents the resize event from firing immediately when the component mounts (default: false).
    • disableRerender: If true, the hook will not trigger a React re-render; only the onResize callback will be executed (default: false).
    • refreshMode: Sets the update strategy to 'throttle' or 'debounce'. If undefined, the callback fires every frame (default: undefined).
    • refreshRate: The timeout or interval (in ms) used when a refreshMode is set (default: undefined).
    • refreshOptions: Additional parameters for the refresh strategy (e.g., { leading: boolean, trailing: boolean }).
    • observerOptions: Standard ResizeObserverOptions passed to the underlying ResizeObserver.observe method.
    type Props = {
      onResize?: OnResizeCallback;
      handleHeight?: boolean;
      handleWidth?: boolean;
      skipOnMount?: boolean;
      disableRerender?: boolean;
      refreshMode?: RefreshModeType;
      refreshRate?: number;
      refreshOptions?: RefreshOptionsType;
      observerOptions?: ResizeObserverOptions;
    };
  8. Understand the ResizePayload structure

    master

    The onResize callback receives a ResizePayload object. This object's structure depends on whether the observed element is currently mounted:

    • When mounted: { width: number; height: number; entry: ResizeObserverEntry }
    • When unmounted: { width: null; height: null; entry: null }
    export type ResizePayload =
      | { width: number; height: number; entry: ResizeObserverEntry }
      | { width: null; height: null; entry: null };
  9. Use the useResizeDetector hook return type

    master

    The useResizeDetector hook returns an object of type UseResizeDetectorReturn<T>, which contains the current dimensions and a ref callback to attach to the target element.

    • width: The current width of the element (number or undefined).
    • height: The current height of the element (number or undefined).
    • ref: A callback ref (OnRefChangeType) used to connect the hook to a DOM element.
    export interface UseResizeDetectorReturn<T> extends Dimensions {
      ref: OnRefChangeType<T>;
    }
    
    export type Dimensions = {
      height?: number;
      width?: number;
    };