Package Exports
- @react-hook/resize-observer
- @react-hook/resize-observer/package.json
Readme
useResizeObserver()
npm i @react-hook/resize-observer
A React hook that fires a callback whenever ResizeObserver detects a change to its size.
Features
- Uses a single
ResizeObserver
for tracking all elements used by the hooks. This approach is astoundingly more performant than using anResizeObserver
per element, as most hook implementations do. - Uses [
resize-observer-polyfill
] as a ponyfill whenResizeObserver
isnt' supported by the current browser. - Automatically unobserves the target element when the hook unmounts.
- You don't have to wrap your callback in
useCallback()
because any mutations are handled by the hook.
Quick Start
Check out an example on CodeSandbox
import * as React from 'react'
import useResizeObserver from '@react-hook/resize-observer'
const MyComponent = () => {
const target = React.useRef(null)
const [{width, height}, setSize] = React.useState()
if (!size && target.current) {
setSize(target.current.getBoundingClientRect())
}
// Where the magic happens
useResizeObserver(target, (entry) => setSize(entry.contentRect))
return <pre ref={target}>{JSON.stringify({width, height}, null, 2)</pre>}
}
API
useResizeObserver(target, callback)
function useResizeObserver<T extends HTMLElement>(
target: React.RefObject<T> | T | null,
callback: UseResizeObserverCallback
): ResizeObserver
Argument | Type | Required? | Description |
---|---|---|---|
target |
`React.RefObject |
T | null` |
callback |
UseResizeObserverCallback |
Yes | Invoked with a single ResizeObserverEntry any time the target resizes |
Types
UseResizeObserverCallback
export type UseResizeObserverCallback = (
entry: ResizeObserverEntry,
observer: ResizeObserver
) => any
LICENSE
MIT