A React hook that fires a callback whenever ResizeObserver detects a change to its size

Downloads in past


1,244321.2.68 months ago3 years agoMinified + gzip package size for @react-hook/resize-observer in KB



<img alt="Bundlephobia" src="https://img.shields.io/bundlephobia/minzip/@react-hook/resize-observer?style=for-the-badge&labelColor=24292e">
<img alt="Types" src="https://img.shields.io/npm/types/@react-hook/resize-observer?style=for-the-badge&labelColor=24292e">
<img alt="Build status" src="https://img.shields.io/travis/com/jaredLunde/react-hook?style=for-the-badge&labelColor=24292e">
<img alt="NPM Version" src="https://img.shields.io/npm/v/@react-hook/resize-observer?style=for-the-badge&labelColor=24292e">
<img alt="MIT License" src="https://img.shields.io/npm/l/@react-hook/resize-observer?style=for-the-badge&labelColor=24292e">

npm i @react-hook/resize-observer

A React hook that fires a callback whenever ResizeObserver detects a change to its size.


  • x Uses a single ResizeObserver for tracking all elements used by the hooks.
[This approach is astoundingly more performant](https://groups.google.com/a/chromium.org/forum/#!msg/blink-dev/z6ienONUb5A/F5-VcUZtBAAJ)
than using a `ResizeObserver` per element which most hook implementations do.
by the current browser.
  • x Automatically unobserves the target element when the hook unmounts.
  • x 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
```jsx harmony import as React from 'react' import useResizeObserver from '@react-hook/resize-observer'
const useSize = (target) => { const size, setSize
= React.useState()
React.useLayoutEffect(() => {
}, target)
// Where the magic happens useResizeObserver(target, (entry) => setSize(entry.contentRect)) return size }
const App = () => { const target = React.useRef(null) const size = useSize(target) return (
<pre ref={target}>
  {JSON.stringify({width: size.width, height: size.height}, null, 2)}
) }
## 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 | Yes | A React ref created by useRef() or an HTML element | | callback | UseResizeObserverCallback | Yes | Invoked with a single ResizeObserverEntry any time the target resizes |



export type UseResizeObserverCallback = (
  entry: ResizeObserverEntry,
  observer: ResizeObserver
) => any