본문으로 건너뛰기

useResizeObserver

ref를 할당한 타겟 엘리먼트의 DOM 크기 변화를 감지하는 커스텀 훅입니다.

ResizeObserver API를 사용하여 요소의 크기가 변경될 때마다 action 콜백을 호출하고, 현재 크기 정보를 contentRect로 반환합니다.


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) => voidnoop요소의 크기가 변경될 때마다 호출되는 콜백 함수

Returns

NameTypeDescription
refReact.RefObject<T | null>크기 변화를 감지할 타겟 엘리먼트에 연결하는 ref
contentRectContentRect타겟 엘리먼트의 현재 크기 정보 (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}>
브라우저 너비를 줄여보세요. <br />
{`width: ${contentRect.width}, height: ${contentRect.height}`}
</div>
);
};

브라우저 너비를 줄여보세요.
width: 0, height: 0