Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
R

react-resize-detector

> 前端框架
Open source

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

1.3K stars0 likes2 views
WebsiteGitHub

About

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

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

xml
css
.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

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

Quick Start

Basic Usage

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

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

With Resize Callback

typescript
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({
    onResize,
  });

  return 
;
};

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.

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

const CustomComponent = () => {
  const targetRef = useRef(null);
  const { width, height } = useResizeDetector({ targetRef });
  return 
;
};

API Reference

Hook Signature

typescript
useResizeDetector(
  props?: useResizeDetectorProps
): UseResizeDetectorReturn

Props

Prop Type Description Default
onResize (payload: ResizePayload) => void Callback invoked with resize information undefined
handleWidth boolean Trigger updates on width changes true
handleHeight boolean Trigger updates on height changes true
skipOnMount boolean Skip the first resize event when component mounts false
disableRerender boolean Disable re-renders triggered by the hook. Only the onResize callback will be called false
refreshMode 'throttle' | 'debounce' Rate limiting strategy. See es-toolkit docs undefined
refreshRate number Delay in milliseconds for rate limiting 1000
refreshOptions { leading?: boolean; trailing?: boolean } Additional options for throttle/debounce undefined
observerOptions ResizeObserverOptions Options passed to resizeObserver.observe undefined
targetRef MutableRefObject External ref to observe (use with caution) undefined

Advanced Examples

Responsive Component

javascript
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 (
    

  );
};

Chart Resizing

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

Performance Optimization

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

Disable Re-renders

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

const NonRerenderingComponent = () => {
  const { ref } = useResizeDetector({
    // Disable re-renders triggered by the hook
    disableRerender: true,
    // Handle resize events through callback only
    onResize: ({ width, height }) => {
      // Update external state or perform side effects
      // without causing component re-renders
      console.log('Resized to:', width, height);
    },
  });

  return 
;
};

Browser Support

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

For older browsers, consider using a ResizeObserver polyfill.

Testing

javascript
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

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

TypeScriptcross-browserreactreact-resize-observerresize

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category前端框架
PricingOpen source

> Related tools

R
React
用于构建用户界面的 JavaScript 库
V
Vue.js
渐进式 JavaScript 框架
N
Next.js
基于 React 的全栈 Web 框架