A React hook that allows you to use a ResizeObserver to measure an element's size.
Installations
npm install use-resize-observer
Developer Guide
Typescript
Yes
Module System
CommonJS
Node Version
14.20.1
NPM Version
8.12.1
Score
95.3
Supply Chain
93.5
Quality
75.8
Maintenance
100
Vulnerability
100
License
Releases
Contributors
Unable to fetch Contributors
Languages
TypeScript (90.6%)
JavaScript (9.32%)
Shell (0.08%)
Love this project? Help keep it running — sponsor us today! 🚀
Developer
ZeeCoder
Download Statistics
Total Downloads
273,681,996
Last Day
433,411
Last Week
2,308,687
Last Month
9,732,444
Last Year
136,500,804
GitHub Statistics
MIT License
659 Stars
127 Commits
43 Forks
5 Watchers
3 Branches
4 Contributors
Updated on Feb 07, 2025
Bundle Size
2.08 kB
Minified
829.00 B
Minified + Gzipped
Package Meta Information
Latest Version
9.1.0
Package Id
use-resize-observer@9.1.0
Unpacked Size
59.06 kB
Size
13.98 kB
File Count
11
NPM Version
8.12.1
Node Version
14.20.1
Total Downloads
Cumulative downloads
Total Downloads
273,681,996
Last Day
-3.6%
433,411
Compared to previous day
Last Week
3.3%
2,308,687
Compared to previous week
Last Month
57.2%
9,732,444
Compared to previous month
Last Year
25.8%
136,500,804
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
1
Dev Dependencies
50
use-resize-observer
A React hook that allows you to use a ResizeObserver to measure an element's size.
Highlights
- Written in TypeScript.
- Tiny: 648B (minified, gzipped) Monitored by size-limit.
- Exposes an onResize callback if you need more control.
box
option.- Works with SSR.
- Works with CSS-in-JS.
- Supports custom refs in case you had one already.
- Uses RefCallback by default To address delayed mounts and changing ref elements.
- Ships a polyfilled version
- Handles many edge cases you might not even think of. (See this documentation and the test cases.)
- Easy to compose (Throttle / Debounce, Breakpoints)
- Tested in real browsers (Currently latest Chrome, Firefox, Edge, Safari, Opera, IE 11, iOS and Android, sponsored by BrowserStack)
In Action
Install
1yarn add use-resize-observer --dev 2# or 3npm install use-resize-observer --save-dev
Options
Option | Type | Description | Default |
---|---|---|---|
ref | undefined | RefObject | HTMLElement | A ref or element to observe. | undefined |
box | undefined | "border-box" | "content-box" | "device-pixel-content-box" | The box model to use for observation. | "content-box" |
onResize | undefined | ({ width?: number, height?: number }) => void | A callback receiving the element size. If given, then the hook will not return the size, and instead will call this callback. | undefined |
round | undefined | (n: number) => number | A function to use for rounding values instead of the default. | Math.round() |
Response
Name | Type | Description |
---|---|---|
ref | RefCallback | A callback to be passed to React's "ref" prop. |
width | undefined | number | The width (or "blockSize") of the element. |
height | undefined | number | The height (or "inlineSize") of the element. |
Basic Usage
Note that the default builds are not polyfilled! For instructions and alternatives, see the Transpilation / Polyfilling section.
1import React from "react"; 2import useResizeObserver from "use-resize-observer"; 3 4const App = () => { 5 const { ref, width = 1, height = 1 } = useResizeObserver<HTMLDivElement>(); 6 7 return ( 8 <div ref={ref}> 9 Size: {width}x{height} 10 </div> 11 ); 12};
To observe a different box size other than content box, pass in the box
option, like so:
1const { ref, width, height } = useResizeObserver<HTMLDivElement>({ 2 box: "border-box", 3});
Note that if the browser does not support the given box type, then the hook won't report any sizes either.
Box Options
Note that box options are experimental, and as such are not supported by all browsers that implemented ResizeObservers. (See here.)
content-box
(default)
Safe to use by all browsers that implemented ResizeObservers. The hook internally will fall back to contentRect
from
the old spec in case contentBoxSize
is not available.
border-box
Supported well for the most part by evergreen browsers. If you need to support older versions of these browsers however, then you may want to feature-detect for support, and optionally include a polyfill instead of the native implementation.
device-pixel-content-box
Surma has a very good article on how this allows us to do pixel perfect
rendering. At the time of writing, however this has very limited support.
The advices on feature detection for border-box
apply here too.
Custom Rounding
By default this hook passes the measured values through Math.round()
, to avoid re-rendering on every subpixel changes.
If this is not what you want, then you can provide your own function:
Rounding Down Reported Values
1const { ref, width, height } = useResizeObserver<HTMLDivElement>({ 2 round: Math.floor, 3});
Skipping Rounding
1import React from "react"; 2import useResizeObserver from "use-resize-observer"; 3 4// Outside the hook to ensure this instance does not change unnecessarily. 5const noop = (n) => n; 6 7const App = () => { 8 const { 9 ref, 10 width = 1, 11 height = 1, 12 } = useResizeObserver<HTMLDivElement>({ round: noop }); 13 14 return ( 15 <div ref={ref}> 16 Size: {width}x{height} 17 </div> 18 ); 19};
Note that the round option is sensitive to the function reference, so make sure you either use useCallback
or declare your rounding function outside of the hook's function scope, if it does not rely on any hook state.
(As shown above.)
Getting the Raw Element from the Default RefCallback
Note that "ref" in the above examples is a RefCallback
, not a RefObject
, meaning you won't be
able to access "ref.current" if you need the element itself.
To get the raw element, either you use your own RefObject (see later in this doc), or you can merge the returned ref with one of your own:
1import React, { useCallback, useEffect, useRef } from "react"; 2import useResizeObserver from "use-resize-observer"; 3import mergeRefs from "react-merge-refs"; 4 5const App = () => { 6 const { ref, width = 1, height = 1 } = useResizeObserver<HTMLDivElement>(); 7 8 const mergedCallbackRef = mergeRefs([ 9 ref, 10 (element: HTMLDivElement) => { 11 // Do whatever you want with the `element`. 12 }, 13 ]); 14 15 return ( 16 <div ref={mergedCallbackRef}> 17 Size: {width}x{height} 18 </div> 19 ); 20};
Passing in Your Own ref
You can pass in your own ref instead of using the one provided. This can be useful if you already have a ref you want to measure.
1const ref = useRef<HTMLDivElement>(null); 2const { width, height } = useResizeObserver<HTMLDivElement>({ ref });
You can even reuse the same hook instance to measure different elements:
Measuring a raw element
There might be situations where you have an element already that you need to measure.
ref
now accepts elements as well, not just refs, which means that you can do this:
1const { width, height } = useResizeObserver<HTMLDivElement>({ 2 ref: divElement, 3});
Using a Single Hook to Measure Multiple Refs
The hook reacts to ref changes, as it resolves it to an element to observe.
This means that you can freely change the custom ref
option from one ref to
another and back, and the hook will start observing whatever is set in its options.
Opting Out of (or Delaying) ResizeObserver Instantiation
In certain cases you might want to delay creating a ResizeObserver instance.
You might provide a library, that only optionally provides observation features based on props, which means that while you have the hook within your component, you might not want to actually initialise it.
Another example is that you might want to entirely opt out of initialising, when
you run some tests, where the environment does not provide the ResizeObserver
.
You can do one of the following depending on your needs:
- Use the default
ref
RefCallback, or provide a custom ref conditionally, only when needed. The hook will not create a ResizeObserver instance up until there's something there to actually observe. - Patch the test environment, and make a polyfill available as the ResizeObserver. (This assumes you don't already use the polyfilled version, which would switch to the polyfill when no native implementation was available.)
The "onResize" Callback
By the default the hook will trigger a re-render on all changes to the target element's width and / or height.
You can opt out of this behaviour, by providing an onResize
callback function,
which'll simply receive the width and height of the element when it changes, so
that you can decide what to do with it:
1import React from "react"; 2import useResizeObserver from "use-resize-observer"; 3 4const App = () => { 5 // width / height will not be returned here when the onResize callback is present 6 const { ref } = useResizeObserver<HTMLDivElement>({ 7 onResize: ({ width, height }) => { 8 // do something here. 9 }, 10 }); 11 12 return <div ref={ref} />; 13};
This callback also makes it possible to implement your own hooks that report only what you need, for example:
- Reporting only width or height
- Throttle / debounce
- Wrap in
requestAnimationFrame
Hook Composition
As this hook intends to remain low-level, it is encouraged to build on top of it via hook composition, if additional features are required.
Throttle / Debounce
You might want to receive values less frequently than changes actually occur.
Breakpoints
Another popular concept are breakpoints. Here is an example for a simple hook accomplishing that.
Defaults (SSR)
On initial mount the ResizeObserver will take a little time to report on the actual size.
Until the hook receives the first measurement, it returns undefined
for width
and height by default.
You can override this behaviour, which could be useful for SSR as well.
1const { ref, width = 100, height = 50 } = useResizeObserver<HTMLDivElement>();
Here "width" and "height" will be 100 and 50 respectively, until the ResizeObserver kicks in and reports the actual size.
Without Defaults
If you only want real measurements (only values from the ResizeObserver without any default values), then you can just leave defaults off:
1const { ref, width, height } = useResizeObserver<HTMLDivElement>();
Here "width" and "height" will be undefined until the ResizeObserver takes its first measurement.
Container/Element Query with CSS-in-JS
It's possible to apply styles conditionally based on the width / height of an element using a CSS-in-JS solution, which is the basic idea behind container/element queries:
Transpilation / Polyfilling
By default the library provides transpiled ES5 modules in CJS / ESM module formats.
Polyfilling is recommended to be done in the host app, and not within imported libraries, as that way consumers have control over the exact polyfills being used.
That said, there's a polyfilled CJS module that can be used for convenience:
1import useResizeObserver from "use-resize-observer/polyfilled";
Note that using the above will use the polyfill, even if the native ResizeObserver is available.
To use the polyfill as a fallback only when the native RO is unavailable, you can polyfill yourself instead,
either in your app's entry file, or you could create a local useResizeObserver
module, like so:
1// useResizeObserver.ts 2import { ResizeObserver } from "@juggle/resize-observer"; 3import useResizeObserver from "use-resize-observer"; 4 5if (!window.ResizeObserver) { 6 window.ResizeObserver = ResizeObserver; 7} 8 9export default useResizeObserver;
The same technique can also be used to provide any of your preferred ResizeObserver polyfills out there.
Related
License
MIT

No vulnerabilities found.
Reason
no dangerous workflow patterns detected
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
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/release.yml:12: update your workflow using https://app.stepsecurity.io/secureworkflow/ZeeCoder/use-resize-observer/release.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/release.yml:13: update your workflow using https://app.stepsecurity.io/secureworkflow/ZeeCoder/use-resize-observer/release.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/size-limit.yml:13: update your workflow using https://app.stepsecurity.io/secureworkflow/ZeeCoder/use-resize-observer/size-limit.yml/master?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/size-limit.yml:14: update your workflow using https://app.stepsecurity.io/secureworkflow/ZeeCoder/use-resize-observer/size-limit.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/testing.yml:15: update your workflow using https://app.stepsecurity.io/secureworkflow/ZeeCoder/use-resize-observer/testing.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/testing.yml:17: update your workflow using https://app.stepsecurity.io/secureworkflow/ZeeCoder/use-resize-observer/testing.yml/master?enable=pin
- Info: 0 out of 5 GitHub-owned GitHubAction dependencies pinned
- Info: 0 out of 1 third-party GitHubAction dependencies pinned
Reason
0 commit(s) and 1 issue activity found in the last 90 days -- score normalized to 0
Reason
Found 0/29 approved changesets -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/release.yml:1
- Warn: no topLevel permission defined: .github/workflows/size-limit.yml:1
- Warn: no topLevel permission defined: .github/workflows/testing.yml:1
- Info: no jobLevel write permissions found
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
Project has not signed or included provenance with any releases.
Details
- Warn: release artifact v9.1.0 not signed: https://api.github.com/repos/ZeeCoder/use-resize-observer/releases/83918299
- Warn: release artifact v9.1.0-alpha.1 not signed: https://api.github.com/repos/ZeeCoder/use-resize-observer/releases/83741975
- Warn: release artifact v9.0.2 not signed: https://api.github.com/repos/ZeeCoder/use-resize-observer/releases/69340840
- Warn: release artifact v9.0.0 not signed: https://api.github.com/repos/ZeeCoder/use-resize-observer/releases/66913248
- Warn: release artifact v8.0.0 not signed: https://api.github.com/repos/ZeeCoder/use-resize-observer/releases/48620332
- Warn: release artifact v9.1.0 does not have provenance: https://api.github.com/repos/ZeeCoder/use-resize-observer/releases/83918299
- Warn: release artifact v9.1.0-alpha.1 does not have provenance: https://api.github.com/repos/ZeeCoder/use-resize-observer/releases/83741975
- Warn: release artifact v9.0.2 does not have provenance: https://api.github.com/repos/ZeeCoder/use-resize-observer/releases/69340840
- Warn: release artifact v9.0.0 does not have provenance: https://api.github.com/repos/ZeeCoder/use-resize-observer/releases/66913248
- Warn: release artifact v8.0.0 does not have provenance: https://api.github.com/repos/ZeeCoder/use-resize-observer/releases/48620332
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'master'
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 2 are checked with a SAST tool
Reason
39 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-67hx-6x53-jw92
- Warn: Project is vulnerable to: GHSA-qwcr-r2fm-qrc7
- Warn: Project is vulnerable to: GHSA-grv7-fg5c-xmjg
- Warn: Project is vulnerable to: GHSA-x9w5-v3q2-3rhw
- Warn: Project is vulnerable to: GHSA-pxg6-pf52-xh8x
- Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275
- Warn: Project is vulnerable to: GHSA-w573-4hg7-7wgq
- Warn: Project is vulnerable to: GHSA-434g-2637-qmqr
- Warn: Project is vulnerable to: GHSA-49q7-c7j4-3p7m
- Warn: Project is vulnerable to: GHSA-977x-g7h5-7qgw
- Warn: Project is vulnerable to: GHSA-f7q4-pwc6-w24p
- Warn: Project is vulnerable to: GHSA-fc9h-whq2-v747
- Warn: Project is vulnerable to: GHSA-r7qp-cfhv-p84w
- Warn: Project is vulnerable to: GHSA-q9mw-68c2-j6m5
- Warn: Project is vulnerable to: GHSA-jchw-25xp-jwwc
- Warn: Project is vulnerable to: GHSA-cxjh-pqwp-8mfp
- Warn: Project is vulnerable to: GHSA-rc47-6667-2j5j
- Warn: Project is vulnerable to: GHSA-78xj-cgh5-2h22
- Warn: Project is vulnerable to: GHSA-2p57-rm9w-gvfp
- Warn: Project is vulnerable to: GHSA-9c47-m6qq-7p4h
- Warn: Project is vulnerable to: GHSA-76p3-8jx3-jpfq
- Warn: Project is vulnerable to: GHSA-3rfm-jhwj-7488
- Warn: Project is vulnerable to: GHSA-hhq3-ff78-jv3g
- Warn: Project is vulnerable to: GHSA-952p-6rrq-rcjv
- Warn: Project is vulnerable to: GHSA-mwcw-c2x4-8c55
- Warn: Project is vulnerable to: GHSA-7fh5-64p2-3v2j
- Warn: Project is vulnerable to: GHSA-gcx4-mw62-g8wm
- Warn: Project is vulnerable to: GHSA-c2qf-rxjj-qqgw
- Warn: Project is vulnerable to: GHSA-76p7-773f-r4q5
- Warn: Project is vulnerable to: GHSA-25hc-qcg6-38wj
- Warn: Project is vulnerable to: GHSA-qm95-pgcg-qqfq
- Warn: Project is vulnerable to: GHSA-cqmj-92xf-r6r9
- Warn: Project is vulnerable to: GHSA-f5x3-32g6-xq36
- Warn: Project is vulnerable to: GHSA-4wf5-vphf-c2xc
- Warn: Project is vulnerable to: GHSA-72xf-g2v4-qvf3
- Warn: Project is vulnerable to: GHSA-fhg7-m89q-25r3
- Warn: Project is vulnerable to: GHSA-j8xg-fqg3-53r7
- Warn: Project is vulnerable to: GHSA-3h5v-q93c-6h6q
- Warn: Project is vulnerable to: GHSA-f9xv-q969-pqx4
Score
2.3
/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 MoreOther packages similar to use-resize-observer
@react-hook/resize-observer
A React hook that fires a callback whenever ResizeObserver detects a change to its size
@ng-web-apis/resize-observer
A library for declarative use of Resize Observer API with Angular
@yamada-ui/use-resize-observer
Yamada UI useResizeObserver custom hook
use-measure
It's just a React hook for resize-observer, uses resize-observer-polyfill. Inspired by [react-measure](https://github.com/souporserious/react-measure)