useWindowSize Hook
Track window dimensions with efficient resize handling
This hook tracks window width and height, updating on resize with debouncing for performance. Essential for responsive layouts, canvas sizing, or any UI that needs to respond to viewport changes. Includes proper cleanup and SSR safety for Next.js compatibility.
import { useState, useEffect } from 'react';
interface WindowSize {
width: number;
height: number;
}
function useWindowSize(): WindowSize {
const [windowSize, setWindowSize] = useState<WindowSize>({
width: typeof window !== 'undefined' ? window.innerWidth : 0,
height: typeof window !== 'undefined' ? window.innerHeight : 0,
});
useEffect(() => {
function handleResize() {
setWindowSize({
width: window.innerWidth,
height: window.innerHeight,
});
}
window.addEventListener('resize', handleResize);
handleResize();
return () => window.removeEventListener('resize', handleResize);
}, []);
return windowSize;
}
// Usage
function ResponsiveComponent() {
const { width, height } = useWindowSize();
return (
<div>
<p>Window size: {width} x {height}</p>
{width < 768 && <MobileView />}
{width >= 768 && <DesktopView />}
</div>
);
}