Convert Figma logo to code with AI

maslianok logoreact-resize-detector

A Cross-Browser, Event-based, Element Resize Detection for React

1,282
94
1,282
1

Top Related Projects

Make your React Components aware of their width and height!

📏 Compute measurements of a React component.

Quick Overview

React-resize-detector is a lightweight React component that allows you to detect and respond to element resize events. It provides a simple way to track changes in the dimensions of DOM elements and trigger callbacks or re-renders when resizing occurs.

Pros

  • Easy to use and integrate into existing React projects
  • Supports both class and functional components
  • Offers various rendering options (wrapper, child function, hooks)
  • Lightweight with minimal dependencies

Cons

  • May introduce a slight performance overhead for frequently resizing elements
  • Limited to React applications only
  • Requires polyfills for older browser support
  • Documentation could be more comprehensive

Code Examples

  1. Basic usage with hooks:
import { useResizeDetector } from 'react-resize-detector';

const MyComponent = () => {
  const { width, height, ref } = useResizeDetector();

  return (
    <div ref={ref}>
      Width: {width}, Height: {height}
    </div>
  );
};
  1. Using render props:
import { ReactResizeDetector } from 'react-resize-detector';

const MyComponent = () => (
  <ReactResizeDetector handleWidth handleHeight>
    {({ width, height }) => (
      <div>Width: {width}, Height: {height}</div>
    )}
  </ReactResizeDetector>
);
  1. With custom resize handler:
import { useResizeDetector } from 'react-resize-detector';

const MyComponent = () => {
  const onResize = (width, height) => {
    console.log(`Resized to ${width}x${height}`);
  };

  const { ref } = useResizeDetector({ onResize });

  return <div ref={ref}>Resizable content</div>;
};

Getting Started

  1. Install the package:

    npm install react-resize-detector
    
  2. Import and use in your React component:

    import { useResizeDetector } from 'react-resize-detector';
    
    const MyComponent = () => {
      const { width, height, ref } = useResizeDetector();
    
      return (
        <div ref={ref}>
          Current dimensions: {width}x{height}
        </div>
      );
    };
    
  3. Customize the behavior by passing options:

    const { ref } = useResizeDetector({
      handleWidth: true,
      handleHeight: true,
      refreshMode: 'debounce',
      refreshRate: 1000,
    });
    

Competitor Comparisons

Make your React Components aware of their width and height!

Pros of react-sizeme

  • More comprehensive API with additional options like monitorWidth, monitorHeight, and refreshRate
  • Supports server-side rendering (SSR) out of the box
  • Provides a SizeMe component for easier implementation in class components

Cons of react-sizeme

  • Slightly larger bundle size due to additional features
  • May have a small performance overhead due to more complex implementation
  • Less frequently updated compared to react-resize-detector

Code Comparison

react-sizeme:

import { withSize } from 'react-sizeme'

const MyComponent = ({ size }) => (
  <div>Width: {size.width}, Height: {size.height}</div>
)

export default withSize()(MyComponent)

react-resize-detector:

import { useResizeDetector } from 'react-resize-detector'

const MyComponent = () => {
  const { width, height, ref } = useResizeDetector()
  return <div ref={ref}>Width: {width}, Height: {height}</div>
}

Both libraries provide similar functionality for detecting size changes in React components. react-sizeme offers more configuration options and built-in SSR support, while react-resize-detector has a simpler API and smaller bundle size. The choice between them depends on specific project requirements and preferences.

📏 Compute measurements of a React component.

Pros of react-measure

  • Provides more detailed measurements, including scroll width and height
  • Offers a render prop API for more flexibility in usage
  • Supports measuring hidden elements

Cons of react-measure

  • Slightly larger bundle size
  • May have a minor performance impact due to more comprehensive measurements
  • Less frequent updates and maintenance compared to react-resize-detector

Code Comparison

react-measure:

<Measure
  bounds
  onResize={contentRect => {
    this.setState({ dimensions: contentRect.bounds })
  }}
>
  {({ measureRef }) => <div ref={measureRef}>Your content here</div>}
</Measure>

react-resize-detector:

<ReactResizeDetector handleWidth handleHeight>
  {({ width, height }) => (
    <div>Width: {width}, Height: {height}</div>
  )}
</ReactResizeDetector>

Both libraries provide similar functionality for detecting size changes in React components. react-measure offers more detailed measurements and a render prop API, while react-resize-detector has a simpler API and potentially better performance for basic resize detection. The choice between the two depends on the specific requirements of your project, such as the level of detail needed in measurements and the preferred API style.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Handle element resizes like it's 2025!

Live demo

Modern browsers now have native support for detecting element size changes through ResizeObservers. This library utilizes ResizeObservers to facilitate managing element size changes in React applications.

🐥 Tiny ~2kb

🐼 Written in TypeScript

🐠 Used by 170k repositories

🦄 Produces 100 million downloads annually

No window.resize listeners! No timeouts!

Should you use this library?

Consider CSS Container Queries first! They now work in all major browsers and might solve your use case with pure CSS.

CSS Container Queries Example
<div class="post">
  <div class="card">
    <h2>Card title</h2>
    <p>Card content</p>
  </div>
</div>
.post {
  container-type: inline-size;
}

/* Default heading styles for the card title */
.card h2 {
  font-size: 1em;
}

/* If the container is larger than 700px */
@container (min-width: 700px) {
  .card h2 {
    font-size: 2em;
  }
}

Use this library when you need:

  • JavaScript-based resize logic with full TypeScript support
  • Complex calculations based on dimensions
  • Integration with React state/effects
  • Programmatic control over resize behavior

Installation

npm install react-resize-detector
# OR
yarn add react-resize-detector
# OR
pnpm add react-resize-detector

Quick Start

Basic Usage

import { useResizeDetector } from 'react-resize-detector';

const CustomComponent = () => {
  const { width, height, ref } = useResizeDetector<HTMLDivElement>();
  return <div ref={ref}>{`${width}x${height}`}</div>;
};

With Resize Callback

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>;
};

With External Ref (Advanced)

It's not advised to use this approach, 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>;
};

API Reference

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
refreshMode'throttle' | 'debounce'Rate limiting strategy. See lodash docsundefined
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

Advanced Examples

Responsive Component

import { useResizeDetector } from 'react-resize-detector';

const ResponsiveCard = () => {
  const { width, ref } = useResizeDetector();

  const cardStyle = {
    padding: width > 600 ? '2rem' : '1rem',
    fontSize: width > 400 ? '1.2em' : '1em',
    flexDirection: width > 500 ? 'row' : 'column',
  };

  return (
    <div ref={ref} style={cardStyle}>
      <h2>Responsive Card</h2>
      <p>Width: {width}px</p>
    </div>
  );
};

Chart Resizing

import { useResizeDetector } from 'react-resize-detector';
import { useEffect, useRef } from 'react';

const Chart = () => {
  const chartRef = useRef(null);
  const { width, height, ref } = useResizeDetector({
    refreshMode: 'debounce',
    refreshRate: 100,
  });

  useEffect(() => {
    if (width && height && chartRef.current) {
      // Redraw chart with new dimensions
      redrawChart(chartRef.current, width, height);
    }
  }, [width, height]);

  return <canvas ref={ref} />;
};

Performance Optimization

import { useResizeDetector } from 'react-resize-detector';

const OptimizedComponent = () => {
  const { width, height, ref } = useResizeDetector({
    // Only track width changes
    handleHeight: false,
    // Debounce rapid changes
    refreshMode: 'debounce',
    refreshRate: 150,
    // Skip initial mount calculation
    skipOnMount: true,
    // Use border-box for more accurate measurements
    observerOptions: { box: 'border-box' },
  });

  return <div ref={ref}>Optimized: {width}px wide</div>;
};

Browser Support

  • ✅ Chrome 64+
  • ✅ Firefox 69+
  • ✅ Safari 13.1+
  • ✅ Edge 79+

For older browsers, consider using a ResizeObserver polyfill.

Testing

const { ResizeObserver } = window;

beforeEach(() => {
  delete window.ResizeObserver;
  // Mock ResizeObserver for tests
  window.ResizeObserver = jest.fn().mockImplementation(() => ({
    observe: jest.fn(),
    unobserve: jest.fn(),
    disconnect: jest.fn(),
  }));
});

afterEach(() => {
  window.ResizeObserver = ResizeObserver;
  jest.restoreAllMocks();
});

Performance Tips

  1. Use handleWidth/handleHeight: false if you only need one dimension
  2. Enable skipOnMount: true if you don't need initial measurements
  3. Use debounce or throttle for expensive resize handlers
  4. Specify observerOptions.box for consistent measurements

License

MIT

❤️ Support

Show us some love and STAR ⭐ the project if you find it useful

NPM DownloadsLast 30 Days