Rooks
HooksAnimation & Timing

useResizeObserverRef

Observes the size of the element attached to a callback ref.

About

useResizeObserverRef returns a callback ref that connects a ResizeObserver to its current element and forwards entries to the latest callback.

Examples

import { useState } from "react";
import { useResizeObserverRef } from "rooks";

export default function ObservedPanel() {
  const [width, setWidth] = useState(0);
  const [ref] = useResizeObserverRef((entries) => {
    setWidth(entries[0]?.contentRect.width ?? 0);
  });

  return (
    <div
      ref={ref}
      style={{ resize: "horizontal", overflow: "auto", width: 240 }}
    >
      Observed width: {Math.round(width)}px
    </div>
  );
}

Parameters

ArgumentTypeDefaultMeaning
callbackResizeObserverCallback | undefinedrequiredLatest callback for observer notifications.
optionsResizeObserverOptions{ box: "content-box" }Observation box; the hook reads its box property.

Return value

A one-item tuple containing a stable callback ref. Attach it to an HTMLElement.

Behavior and lifecycle

Attaching a node creates an observer and calls observe(node, { box }). Detaching, changing the node or box, and unmounting disconnect the current observer. Callback changes are forwarded through a ref and do not recreate the observer. Observer construction errors are not caught.

Compatibility and accessibility

Server rendering is safe because no node is attached and effects do not run. Clients need ResizeObserver; add a polyfill or fallback for unsupported browsers. Size observation is not itself accessible, so ensure any layout response preserves reading order, focus visibility, and zoom support.

On this page