Skip to main content

Function: useElementSize()

useElementSize<T>(options?): UseElementSizeResult<T>

Defined in: use-element-size.ts:125

Tracks the size of an element with a ResizeObserver and returns it as state, so your component re-renders when the element is resized.

  • 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.
  • Efficient: re-renders only when the width or height actually changes.
  • Box: measures the content box by default; pass box: "border-box" to include padding and border.
  • Values: fractional CSS pixels, exactly as reported by the browser. CSS transforms do not affect them. A display: none element measures 0 x 0.
  • SSR-safe: returns defaultSize on the server, on the first render, and wherever ResizeObserver is unavailable.
  • Cleanup: the observer is disconnected on unmount and when the element or box changes. When the element unmounts, the last measured size is kept.

The first measurement arrives after the element mounts, so the first render (and the server render) uses defaultSize. To combine 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 measured. Defaults to HTMLElement.

Parameters​

options?​

UseElementSizeOptions

Optional box, defaultSize and onResize callback.

Returns​

UseElementSizeResult<T>

The element's width and height, and the ref to attach to it.

Examples​

const { ref, width, height } = useElementSize<HTMLDivElement>();

return (
<div ref={ref}>
{Math.round(width)} x {Math.round(height)}
</div>
);
// Include padding and border, and react to every change
const { ref } = useElementSize<HTMLElement>({
box: "border-box",
onResize: ({ width }) => console.log("new width", width),
});
// Compose your own helpers on top
const useIsNarrow = (limit: number) => {
const { ref, width } = useElementSize<HTMLDivElement>();
return { ref, isNarrow: width > 0 && width < limit };
};

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

See​

ResizeObserver