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
refto 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: noneelement measures0x0. - SSR-safe: returns
defaultSizeon the server, on the first render, and whereverResizeObserveris unavailable. - Cleanup: the observer is disconnected on unmount and when the element
or
boxchanges. 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?
Optional box, defaultSize and onResize callback.
Returns
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.