useWindowSize
현재 브라우저 창의 너비와 높이 정보를 추적하고, 반환하는 커스텀 훅입니다.
SSR 환경에서 hydration 불일치를 방지하며, resize 이벤트가 발생할 때 불 필요한 호출을 방지하기위한 debounce 기능을 제공합니다.
디바운스 대기 시간(debounceWait)을 설정하면 debounce로 동작하며, 설정하지 않으면 즉시 업데이트됩니다.
Code
Interface
typescript
function useWindowSize(debounceWait?: number): {
width: number;
height: number;
}
Usage
Default
typescript
import { useWindowSize } from '@modern-kit/react';
const Example = () => {
const windowSize = useWindowSize();
const boxStyle = useMemo(() => {
return {
width: '100%',
background: '#439966',
fontSize: '2rem',
color: '#fff',
}
}, []);
return (
<div style={boxStyle}>
브라우저 크기를 줄여보세요. <br />
width: {windowSize.width}px <br />
height: {windowSize.height}px
</div>
);
};
브라우저 크기를 줄여보세요.
width: 0px
height: 0px
width: 0px
height: 0px
Debounce
typescript
import { useWindowSize } from '@modern-kit/react';
const DebounceExample = () => {
const windowSize = useWindowSize(300);
const boxStyle = useMemo(() => {
return {
width: '100%',
background: '#0067A3',
fontSize: '2rem',
color: '#fff',
}
}, []);
return (
<div style={boxStyle}>
브라우저 크기를 줄여보세요. <br />
width: {windowSize.width}px <br />
height: {windowSize.height}px
</div>
);
};
브라우저 크기를 줄여보세요.
width: 0px
height: 0px
width: 0px
height: 0px