Skip to main content

useWindowSize

A custom hook that tracks and returns the current browser window's width and height.

It prevents hydration mismatches in SSR environments, and provides a debounce feature to prevent unnecessary calls when resize events fire.

If a debounce wait time (debounceWait) is set, it operates with debouncing; if not set, it updates immediately.


Code

🔗 View source code


Interface

typescript
function useWindowSize(debounceWait?: number): {
width: number;
height: number;
}

Options

NameTypeDefaultDescription
debounceWaitnumber-Debounce wait time in milliseconds. If not set, updates immediately.

Returns

NameTypeDescription
widthnumberCurrent browser window width (px)
heightnumberCurrent browser window height (px)

Usage

Basic Usage

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}>
Try resizing the browser window. <br />
width: {windowSize.width}px <br />
height: {windowSize.height}px
</div>
);
};
Try resizing the browser window.
width: 0px
height: 0px

Debounce Usage

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}>
Try resizing the browser window. <br />
width: {windowSize.width}px <br />
height: {windowSize.height}px
</div>
);
};
Try resizing the browser window.
width: 0px
height: 0px