apps/mantine.dev/src/pages/hooks/use-resize-observer.mdx
import { UseResizeObserverDemos } from '@docs/demos'; import { Layout } from '@/layout'; import { MDX_DATA } from '@/mdx';
export default Layout(MDX_DATA.useResizeObserver);
The use-resize-observer hook returns a ref object that should be passed to the observed element, and the current element content rect, as returned by the ResizeObserver's callback entry.contentRect.
See the Resize Observer API documentation to learn more.
On the first render (as well as during SSR), or when no element is being observed, all of the properties are equal to 0.
import { useResizeObserver } from '@mantine/hooks';
function Demo() {
const [ref, rect] = useResizeObserver();
return <div ref={ref}>Observed</div>;
}
See also the use-element-size hook in case you need to subscribe only to width and height.
type ObserverRect = Omit<DOMRectReadOnly, 'toJSON'>;
function useResizeObserver<T extends HTMLElement = any>(
options?: ResizeObserverOptions
): readonly [React.RefCallback<T | null>, ObserverRect];