Skip to main content

useResizeObserver

A custom hook that detects DOM size changes of the target element assigned a ref.

It uses the ResizeObserver API to invoke the action callback whenever the element's size changes, and returns the current size information via contentRect.


Code

🔗 View source code


Interface

typescript
type ContentRect = Omit<DOMRectReadOnly, 'toJSON'>;

const useResizeObserver: <T extends HTMLElement>(
action?: (entry: ResizeObserverEntry) => void
) => {
ref: React.RefObject<T | null>;
contentRect: ContentRect;
};

Options

NameTypeDefaultDescription
action(entry: ResizeObserverEntry) => voidnoopCallback function invoked whenever the element's size changes

Returns

NameTypeDescription
refReact.RefObject<T | null>Ref to attach to the target element to observe size changes
contentRectContentRectCurrent size information of the target element (width, height, top, left, right, bottom, x, y)

Remarks


Usage

typescript
import { useResizeObserver } from '@modern-kit/react';

const Example = () => {
const { ref, contentRect } = useResizeObserver<HTMLDivElement>((entry) => {
console.log('resize', entry);
});

const boxStyle = useMemo(() => {
return {
width: '100%',
height: '400px',
background: '#439966',
fontSize: '2rem',
color: '#fff',
}
}, []);

return (
<div
ref={ref}
style={boxStyle}>
Try resizing the browser window. <br />
{`width: ${contentRect.width}, height: ${contentRect.height}`}
</div>
);
};

Try resizing the browser window.
width: 0, height: 0