Installations
npm install @pmbs/react-resize-detector
Developer Guide
Typescript
Yes
Module System
CommonJS
Node Version
16.14.0
NPM Version
8.3.1
Releases
Contributors
Unable to fetch Contributors
Languages
TypeScript (89.72%)
CSS (5.91%)
JavaScript (3.46%)
HTML (0.91%)
Love this project? Help keep it running — sponsor us today! 🚀
Developer
Download Statistics
Total Downloads
1,515
Last Day
1
Last Week
31
Last Month
72
Last Year
737
GitHub Statistics
MIT License
1,267 Stars
529 Commits
92 Forks
10 Watchers
4 Branches
37 Contributors
Updated on Feb 10, 2025
Package Meta Information
Latest Version
7.0.0
Package Id
@pmbs/react-resize-detector@7.0.0
Unpacked Size
389.13 kB
Size
90.87 kB
File Count
13
NPM Version
8.3.1
Node Version
16.14.0
Total Downloads
Cumulative downloads
Total Downloads
1,515
Last Day
0%
1
Compared to previous day
Last Week
342.9%
31
Compared to previous week
Last Month
166.7%
72
Compared to previous month
Last Year
127.5%
737
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
2
Dev Dependencies
24
Handle element resizes like it's 2022!
Live demo
Nowadays browsers support element resize handling natively using ResizeObservers. The library uses these observers to help you handle element resizes in React.
🐥 Tiny ~3kb
🐼 Written in TypeScript
🦁 Supports Function and Class Components
🐠 Used by 20k+ repositories
🦄 Generating 35M+ downloads/year
No window.resize
listeners! No timeouts! No 👑 viruses! :)
TypeScript-lovers notice: starting from v6.0.0 you may safely remove @types/react-resize-detector
from you deps list.
Installation
1npm i react-resize-detector 2// OR 3yarn add react-resize-detector
and
1import ResizeObserver from 'react-resize-detector';
Examples
Starting from v6.0.0 there are 3 recommended ways to work with resize-detector
library:
1. React hook (new in v6.0.0)
1import { useResizeDetector } from 'react-resize-detector'; 2 3const CustomComponent = () => { 4 const { width, height, ref } = useResizeDetector(); 5 return <div ref={ref}>{`${width}x${height}`}</div>; 6};
With props
1import { useResizeDetector } from 'react-resize-detector'; 2 3const CustomComponent = () => { 4 const onResize = useCallback(() => { 5 // on resize logic 6 }, []); 7 8 const { width, height, ref } = useResizeDetector({ 9 handleHeight: false, 10 refreshMode: 'debounce', 11 refreshRate: 1000, 12 onResize 13 }); 14 15 return <div ref={ref}>{`${width}x${height}`}</div>; 16};
With custom ref
1import { useResizeDetector } from 'react-resize-detector'; 2 3const CustomComponent = () => { 4 const targetRef = useRef(); 5 const { width, height } = useResizeDetector({ targetRef }); 6 return <div ref={targetRef}>{`${width}x${height}`}</div>; 7};
2. HOC pattern
1import { withResizeDetector } from 'react-resize-detector'; 2 3const CustomComponent = ({ width, height }) => <div>{`${width}x${height}`}</div>; 4 5export default withResizeDetector(CustomComponent);
3. Child Function Pattern
1import ReactResizeDetector from 'react-resize-detector'; 2 3// ... 4 5<ReactResizeDetector handleWidth handleHeight> 6 {({ width, height }) => <div>{`${width}x${height}`}</div>} 7</ReactResizeDetector>;
Full example (Class Component)
1import React, { Component } from 'react'; 2import { withResizeDetector } from 'react-resize-detector'; 3 4const containerStyles = { 5 height: '100vh', 6 display: 'flex', 7 alignItems: 'center', 8 justifyContent: 'center' 9}; 10 11class AdaptiveComponent extends Component { 12 state = { 13 color: 'red' 14 }; 15 16 componentDidUpdate(prevProps) { 17 const { width } = this.props; 18 19 if (width !== prevProps.width) { 20 this.setState({ 21 color: width > 500 ? 'coral' : 'aqua' 22 }); 23 } 24 } 25 26 render() { 27 const { width, height } = this.props; 28 const { color } = this.state; 29 return <div style={{ backgroundColor: color, ...containerStyles }}>{`${width}x${height}`}</div>; 30 } 31} 32 33const AdaptiveWithDetector = withResizeDetector(AdaptiveComponent); 34 35const App = () => { 36 return ( 37 <div> 38 <p>The rectangle changes color based on its width</p> 39 <AdaptiveWithDetector /> 40 </div> 41 ); 42}; 43 44export default App;
Full example (Functional Component)
1import React, { useState, useEffect } from 'react'; 2import { withResizeDetector } from 'react-resize-detector'; 3 4const containerStyles = { 5 height: '100vh', 6 display: 'flex', 7 alignItems: 'center', 8 justifyContent: 'center' 9}; 10 11const AdaptiveComponent = ({ width, height }) => { 12 const [color, setColor] = useState('red'); 13 14 useEffect(() => { 15 setColor(width > 500 ? 'coral' : 'aqua'); 16 }, [width]); 17 18 return <div style={{ backgroundColor: color, ...containerStyles }}>{`${width}x${height}`}</div>; 19}; 20 21const AdaptiveWithDetector = withResizeDetector(AdaptiveComponent); 22 23const App = () => { 24 return ( 25 <div> 26 <p>The rectangle changes color based on its width</p> 27 <AdaptiveWithDetector /> 28 </div> 29 ); 30}; 31 32export default App;
We still support other ways to work with this library, but in the future consider using the ones described above. Please let me know if the examples above don't fit your needs.
Performance optimization
This library uses the native ResizeObserver API.
DOM nodes get attached to ResizeObserver.observe
every time the component mounts and every time any property gets changed.
It means you should try to avoid passing anonymous functions to ResizeDetector
, because they will trigger the whole initialization process every time the component rerenders. Use useCallback
whenever it's possible.
1// WRONG - anonymous function 2const { ref, width, height } = useResizeDetector({ 3 onResize: () => { 4 // on resize logic 5 } 6}); 7 8// CORRECT - `useCallback` approach 9const onResize = useCallback(() => { 10 // on resize logic 11}, []); 12 13const { ref, width, height } = useResizeDetector({ onResize });
Refs
The below explanation doesn't apply to useResizeDetector
The library is trying to be smart and does not add any extra DOM elements to not break your layouts. That's why we use findDOMNode
method to find and attach listeners to the existing DOM elements. Unfortunately, this method has been deprecated and throws a warning in StrictMode.
For those who want to avoid this warning, we are introducing an additional property - targetRef
. You have to set this prop as a ref
of your target DOM element and the library will use this reference instead of searching the DOM element with help of findDOMNode
HOC pattern example
1import { withResizeDetector } from 'react-resize-detector'; 2 3const CustomComponent = ({ width, height, targetRef }) => <div ref={targetRef}>{`${width}x${height}`}</div>; 4 5export default withResizeDetector(CustomComponent);
Child Function Pattern example
1import ReactResizeDetector from 'react-resize-detector'; 2 3// ... 4 5<ReactResizeDetector handleWidth handleHeight> 6 {({ width, height, targetRef }) => <div ref={targetRef}>{`${width}x${height}`}</div>} 7</ReactResizeDetector>;
API
Prop | Type | Description | Default |
---|---|---|---|
onResize | Func | Function that will be invoked with width and height arguments | undefined |
handleWidth | Bool | Trigger onResize on width change | true |
handleHeight | Bool | Trigger onResize on height change | true |
skipOnMount | Bool | Do not trigger onResize when a component mounts | false |
refreshMode | String | Possible values: throttle and debounce See lodash docs for more information. undefined - callback will be fired for every frame | undefined |
refreshRate | Number | Use this in conjunction with refreshMode . Important! It's a numeric prop so set it accordingly, e.g. refreshRate={500} | 1000 |
refreshOptions | Object | Use this in conjunction with refreshMode . An object in shape of { leading: bool, trailing: bool } . Please refer to lodash's docs for more info | undefined |
observerOptions | Object | These options will be used as a second parameter of resizeObserver.observe method. | undefined |
targetRef | Ref | Use this prop to pass a reference to the element you want to attach resize handlers to. It must be an instance of React.useRef or React.createRef functions | undefined |
Testing with Enzyme and Jest
Thanks to @Primajin for posting this snippet
1const { ResizeObserver } = window; 2 3beforeEach(() => { 4 delete window.ResizeObserver; 5 window.ResizeObserver = jest.fn().mockImplementation(() => ({ 6 observe: jest.fn(), 7 unobserve: jest.fn(), 8 disconnect: jest.fn() 9 })); 10 11 wrapper = mount(<MyComponent />); 12}); 13 14afterEach(() => { 15 window.ResizeObserver = ResizeObserver; 16 jest.restoreAllMocks(); 17}); 18 19it('should do my test', () => { 20 // [...] 21});
License
MIT
❤️
Show us some love and STAR ⭐ the project if you find it useful

No vulnerabilities found.
Reason
16 commit(s) and 2 issue activity found in the last 90 days -- score normalized to 10
Reason
no binaries found in the repo
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
2 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-67mh-4wv8-2f99
- Warn: Project is vulnerable to: GHSA-vg6x-rcgg-rjx6
Reason
Found 3/5 approved changesets -- score normalized to 6
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 28 are checked with a SAST tool
Score
5.6
/10
Last Scanned on 2025-02-10
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More