Skip to main content

Function: useResizeObserver()

useResizeObserver<T>(callback, options?): (element) => void

Defined in: use-resize-observer.ts:100

Runs a callback whenever an element is resized, using a ResizeObserver. It is the low-level building block behind size-tracking hooks: it hands you the raw ResizeObserverEntry and holds no state, so it never re-renders your component on its own. Need the size as state? Use useElementSize.

  • Usage: attach the returned ref to any element. It is a callback ref, so it also works when the element mounts later, is rendered conditionally, or is swapped for another one.
  • Raw entry: the callback gets the ResizeObserverEntry, so you choose what to read (contentRect, borderBoxSize, devicePixelContentBoxSize, ...) and where to put it (state, a ref, a canvas, a store).
  • Latest callback: the callback may change on every render without re-observing the element.
  • Options: pick the observed box, or pause with enabled: false.
  • SSR-safe: does nothing on the server, and wherever ResizeObserver is unavailable.
  • Cleanup: the observer is disconnected on unmount, when the element changes, when box changes, and when enabled becomes false.

A ResizeObserver reports once as soon as observing starts, so the callback runs with the initial size after the element mounts. To combine the ref with another ref, call both from a function ref, for example ref={(el) => { ref(el); myRef.current = el; }}.

Type Parameters​

T​

T extends Element = HTMLElement

The type of element being observed. Defaults to HTMLElement.

Parameters​

callback​

ResizeObserverHandler

Called with the ResizeObserverEntry and the observer on every resize.

options?​

UseResizeObserverOptions

Optional box and enabled settings.

Returns​

A callback ref to attach to the element you want to observe.

(element) => void

Examples​

const ref = useResizeObserver<HTMLDivElement>((entry) => {
console.log("width", entry.contentRect.width);
});

return <div ref={ref} />;
// Keep a canvas sharp by reading device pixels, without re-rendering
const ref = useResizeObserver<HTMLCanvasElement>(
(entry) => {
const size = entry.devicePixelContentBoxSize?.[0];
if (!size) return;
entry.target.width = size.inlineSize;
entry.target.height = size.blockSize;
},
{ box: "device-pixel-content-box" }
);
// Compose your own helpers on top
const useWidth = (enabled = true) => {
const [width, setWidth] = useState(0);
const ref = useResizeObserver<HTMLElement>(
(entry) => setWidth(entry.contentRect.width),
{ enabled }
);
return { ref, width };
};

For a live, editable example, see the useResizeObserver docs page.

See​

ResizeObserver