https://github.com/alloc/use-element-size
Track the size of a react-dom element in 540 bytes (without ResizeObserver)
https://github.com/alloc/use-element-size
react-dom react-hooks reactjs
Last synced: 10 months ago
JSON representation
Track the size of a react-dom element in 540 bytes (without ResizeObserver)
- Host: GitHub
- URL: https://github.com/alloc/use-element-size
- Owner: alloc
- License: mit
- Archived: true
- Created: 2020-08-14T00:19:18.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2022-12-11T17:48:59.000Z (about 3 years ago)
- Last Synced: 2025-03-27T02:18:28.237Z (12 months ago)
- Topics: react-dom, react-hooks, reactjs
- Language: TypeScript
- Homepage:
- Size: 71.3 KB
- Stars: 16
- Watchers: 2
- Forks: 2
- Open Issues: 3
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# use-element-size
Track the size of a `react-dom` element (without `ResizeObserver`).
Only **540 bytes** min+gzip!
## Usage
```tsx
import React from 'react'
import { useElementSize } from 'use-element-size'
const Example = () => {
const ref = useElementSize((size, prevSize, elem) => {
console.log({ size, prevSize, elem })
})
return (
)
}
```
## Quirks
- ⚠️ Be sure the tracked element **never** has `position: static`.
- The `size` parameter is `null` when the tracked element is unmounted.
- The `prevSize` parameter is `null` when the tracked element was just mounted.
- Tracking stops when `useElementSize` is passed `false/null/undefined` instead of a function.
- The callback waits until the next `requestAnimationFrame` tick before running.
- The `Size` and `SizeCallback` types are exported for your convenience.
## Demo
https://codesandbox.io/s/use-element-size-demo-dszk1?file=/src/index.tsx